我正在使用“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);
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
您的dummy函数是错误的 \xe2\x80\x93setTimeout不会返回任何可等待的内容,因此它会立即返回。
由 Promise 驱动的delay函数看起来像
const delay = timeToWait => new Promise(resolve => setTimeout(resolve, timeToWait));\nRun Code Online (Sandbox Code Playgroud)\n\n所以尝试用它代替你的dummy, ie
console.log(\'hello\');\nawait delay(100);\nconsole.log(\'world\');\nRun Code Online (Sandbox Code Playgroud)\n\n编辑:总而言之,您的代码可能应该看起来像
\n\nconst delay = timeToWait => new Promise(resolve => setTimeout(resolve, timeToWait));\n// Iterate over the minutes off and get aggregate data\nconst computeAggregate = async (model, sym) => {\n const symbols = await model\n .find({ symbol: sym })\n .sort({ trade_ts: 1 })\n .exec();\n const currentMinute = symbols[0].minutes_offs;\n for (let sym of symbols) {\n await delay(Math.random() * 1000);\n console.log("End wait", val);\n }\n};\nRun Code Online (Sandbox Code Playgroud)\n\n所以你没有混合await和.then()。
| 归档时间: |
|
| 查看次数: |
3901 次 |
| 最近记录: |