0

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

Carlos Delgado
  • 159
  • 1
  • 2
  • 15
  • 2
    `.then(result => {` is not async... – CertainPerformance Oct 25 '19 at 00:28
  • @CertainPerformance I've tried `.then(async result => {` // and now the program runs but is not giving me the results I'm expecting, it's giving me 10 seconds then 10 seconds later 2nd result and then 10seconds later the 3rd result and it should be 10 seconds 1st result, 20 second after the 2nd and 30 seconds after the 3rd result – Carlos Delgado Oct 25 '19 at 00:32
  • 1
    Your algorithm is off - `(i) * 10000;` in a loop results in 10sec, then 20sec, then 30sec, but you want 10sec, then 30sec, then 60sec. Or, even easier, just `await` the call of `otherTest` – CertainPerformance Oct 25 '19 at 00:34
  • `await` the call of `otherTest` and put `.then(async result =>` solve the problem thanks! – Carlos Delgado Oct 25 '19 at 00:36

0 Answers0