0

I can't seem to figure out why the loop is executing at full speed even though the await is in the loop.

   model.collection.distinct("symbol", async function (error, distSymbols) {
        // iterate over the unique symbols and compute aggregate
        for (const symbol of distSymbols) {
            //
            //await computeAggregate(model, symbol);
            await dummy(Math.random() * 1000);
            console.log(symbol); //This will execute before any of the dummy awaits
        }
        res.json("success");
    });
});

const dummy = async(timeToWait) => {
    setTimeout(() => {
        console.log("I am waiting for", timeToWait);
        return true;
    }, timeToWait);
}
user2130951
  • 2,601
  • 4
  • 31
  • 58
  • 1
    Possible duplicate of [How do I convert an existing callback API to promises?](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises) – CertainPerformance Mar 11 '19 at 08:23
  • `dummy` resolves immediately, use the Promise constructor instead – CertainPerformance Mar 11 '19 at 08:23
  • It's because the `return true;` returns from the `setTimeout` callback, not from `dummy` (that returns instantly after setting the timeout) – Kaddath Mar 11 '19 at 08:24

1 Answers1

0

Your dummy() function isn't working as expected. It resolves instantly just after setting the timeout, it won't wait for it.

Use Promises to wait for the timeout to finish. There is no need to add the async keyword as the function already returns a Promise.

function dummy(timeToWait) {
   return new Promise(resolve => setTimeout(resolve, timeToWait));
}
Kapcash
  • 6,377
  • 2
  • 18
  • 40