我有以下功能。它获得一组属性,并将循环遍历它们以将每个属性放入数据库中。但循环将与await
声明自动杀:为什么要“等待”在现代Javascript中打破或杀死for循环?
async function importAttributeRecords(attributeValues, languageId, attributes, dataStorage, tx) {
for(let attr of attributes) {
console.log("Persist", attr)
try {
await importAttributeRecord(attributeValues, languageId, attr, dataStorage, tx)
}
catch(err) {
console.log(err);
}
console.log("After persisting");
}
}
到await
的第一次调用将被执行,但之后的第二console.log
声明将不会出现。 此外,循环将立即退出。
即使返回承诺,如何在同一个循环中同步执行像importAttributeRecord()
这样的函数? 为什么使用“等待”循环危险?
你的意思是跟第二个日志调用一个输出:''在保持后''?抛出异常吗? – k0pernikus
需要更多[mcve]。 – melpomene
循环未被杀死。它被搁置,当你“等待”承诺时会恢复。承诺是异步的。您不能将它们视为同步。 –