Home > Net >  Async function don't run as expected
Async function don't run as expected

Time:09-07

I do have a problem with my asnyc functions, because they are not running one after another. That is my code:

async function main() {
  async function func() {
    for (let i = 0; i < array.length; i  ) {
      var result_amount = await calc(array[i]);
      if (result_amount > amount_start * 0.5) {
        console.log(
          "i: ",
          i,
          "Route: ",
          array[i][6],
          "amount_start: ",
          amount_start,
          "amount: ",
          result_amount
        );
      }
    }
  }

  const POLLING_INTERVAL = process.env.POLLING_INTERVAL || 1000; 
  Monitor = setInterval(async () => {
    await func();
  }, POLLING_INTERVAL);
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});

So there I am calling calc with the i-th element of my array. Lets say array has length 10. Then the code does not execute i = 0, then i = 1, then i = 2 ando so an, instead it is doing like i = 0, then i = 1, but then again i = 0. Why does this happen and how can I avoid this?

Thank you!

CodePudding user response:

It looks to me you are not handling the promise correctly inside setInterval. You need to "promisify" the setInterval method like so (keep in mind, I did not test this out but it should work):

return new Promise(function(resolve, reject) {
    setInterval(async function() {
      await func()
      resolve();
    }, POLLING_INTERVAL)
})

CodePudding user response:

I executed your code mocking some of data and for me it looks like it is going through all array.

I assume that there is some issue with one of the functions you have defined (probably calc() which has some timeout inside)

  • Related