How to delay a fetch script in netlify function?

31 views Asked by At

I have tried different methods like setttimeout and for loop but the script wont fire.

exports.handler = async function (event, context, callback) {

  const reqbody = JSON.parse(event.body);

  try {
    var yd = new URLSearchParams();
    yd.append("Author", "thea");
    yd.append("Body", reqbody.body);

    const postmessageoptions = {
      method: 'POST',
      headers: {
        accept: 'application/json',
        'content-type': 'application/x-www-form-urlencoded',
        authorization: 'Basic ' + process.env.BASIC_TOKEN_TWILIO
      },
      body: yd
    };

    function createCustomTimeout(seconds) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve();
        }, seconds * 1000);
      });
    }

    async function testing() {
      console.log('testing function has been triggered');
      await createCustomTimeout(5);
      console.log('success');
      await fetch('https://conversations.twilio.com/v1/Conversations/' + reqbody.sid + '/Messages', postmessageoptions)
    }

    testing();
    // end post message


    return {
      headers: {
        "content-type": "application/json",
        "Access-Control-Allow-Origin": "*",
      },
      statusCode: 200,
      body: JSON.stringify('success'),
    };

  } catch (error) {

    return {
      headers: {
        "content-type": "application/json",
        "Access-Control-Allow-Origin": "*",
      },
      statusCode: 500,
      body: JSON.stringify(error),
    }


  }



};

I want to delay the fetch like 5 seconds, but it returns success without firing the fetch. I could see that console.log('success') fires on console, but not the fetch.

Please help me.

1

There are 1 answers

0
BadPiggie On

The testing is an async function, but you have called it without await keyword. So the program reaches the return statement as soon as calling testing() which will terminate the lambda and also the fetch requests.

exports.handler = async function (event, context, callback) {

   // your code

   await testing();

   // rest of your code
}