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.
The
testingis anasyncfunction, but you have called it withoutawaitkeyword. So the program reaches thereturnstatement as soon as callingtesting()which will terminate thelambdaand also thefetchrequests.