For循环不等待

时间:2019-03-11 10:59:35

标签: node.js

我正在使用“ for of”循环。但是,它仍然不等待虚拟函数退出。我当时的假设是,等待将等待“虚拟”功能完成,然后使用“ for of”。

日志输出:

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);
            }
        }

    });

}

2 个答案:

答案 0 :(得分:3)

您的dummy函数是错误的– setTimeout不会返回任何可等待的内容,因此会立即返回。

由承诺驱动的delay函数看起来像

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

因此请尝试代替您的dummy,即

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

编辑:总而言之,您的代码应该看起来像

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);
  }
};

因此您不会混用await.then()

答案 1 :(得分:0)

dummy立即解决,因为它返回的承诺与setTimeout无关。 setTimeout不会返回可以await实现的承诺。如here所述,延迟承诺应为:

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