user2130951
user2130951

Reputation: 2741

For loop not waiting for await

I am using the "for of" loop. But still, it's not waiting for the dummy function to exit. I was under the assumption that await would wait for the "dummy" function to finish and then use "for of".

Log output:

End wait true
starting wait
End wait true
starting wait
End wait true
I am waiting for 925.6301720227887
I am waiting for 923.6969211579702
I am waiting for 962.0987671698102
etc...



const dummy = async(timeToWait) => {
    await setTimeout(() => {
        console.log("I am waiting for", timeToWait);

    }, timeToWait);
    return Promise.resolve(true);
}

    // Iterate over the minutes off and get aggregate data
    const computeAggregate = async (model, sym) => {


    await model.find({"symbol": sym})
    .sort({trade_ts:1}).exec()
    .then(async (symbol) => {
        var firstDoc = symbol[0];
        currentMinute = symbol[0].minutes_offs;
        var rec = [];

        for (sym of symbol) {

            console.log("starting wait");
            let val = await dummy(Math.random() * 1000);
            console.log("End wait", val);
            }
        }

    });

}

Upvotes: 2

Views: 4416

Answers (2)

AKX
AKX

Reputation: 168883

Your dummy function is wrong – setTimeout doesn't return anything awaitable, so it returns immediately.

A promise-powered delay function looks like

const delay = timeToWait => new Promise(resolve => setTimeout(resolve, timeToWait));

so try that instead of your dummy, i.e.

console.log('hello');
await delay(100);
console.log('world');

EDIT: all in all, your code should maybe look like

const delay = timeToWait => new Promise(resolve => setTimeout(resolve, timeToWait));
// Iterate over the minutes off and get aggregate data
const computeAggregate = async (model, sym) => {
  const symbols = await model
    .find({ symbol: sym })
    .sort({ trade_ts: 1 })
    .exec();
  const currentMinute = symbols[0].minutes_offs;
  for (let sym of symbols) {
    await delay(Math.random() * 1000);
    console.log("End wait", val);
  }
};

so you're not mixing await and .then().

Upvotes: 6

Estus Flask
Estus Flask

Reputation: 222369

dummy resolves immediately because a promise it returns and setTimeout aren't related. setTimeout doesn't return a promise that could be awaited. As explained here, a delayed promise should be:

const dummy = async(timeToWait) => {
    await new Promise(resolve => setTimeout(resolve, timeToWait));
    console.log("I am waiting for", timeToWait);
    return true;
}

Upvotes: 0

Related Questions