I'm trying to call an asynchronous function from a .then and inside and if statement but I can't because it says await can only be called in async functions (I knew this) is there a way for me to accomplish this?
I've tried to put chain the result of the promise but it didn't work either I'm getting this error:
if (i < 5) await queueSleep(time1);
^^^^^
SyntaxError: await is only valid in async function
and this is my code:
async function queueSleep(time) {
return new Promise((resolve) => {
setTimeout(() => {
console.log(`After ${time / 1000} seconds`);
resolve();
}, time);
});
}
async function otherTest() {
return new Promise((resolve) => {
resolve('Hello');
})
}
async function main() {
for (let i = 1; i <= 3; i++) {
let time1 = (i) * 10000;
otherTest()
.then(result => {
console.log(result)
if (i < 5)
await queueSleep(time1); // I need this to wait on each call before call the queueSleep again
});
}
}
main();
I expect that the complete program takes in that example 60 seconds to complete, first 10 seconds then wait 20 seconds then wait 30 seconds