【发布时间】:2018-02-24 19:58:30
【问题描述】:
我有以下功能。它获取一个属性数组,并将在循环中迭代它们以将每个属性放入数据库中。但是循环会被await 语句自动终止:
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() 这样的函数?
为什么对循环使用“等待”很危险?
【问题讨论】:
-
你的意思是第二个日志调用输出:
"After persisting"?是否抛出异常? -
循环没有被杀死。它被搁置,并在您
await承诺时恢复。 Promise 是异步的。您不能将它们视为同步的。 -
它
importAttributeRecord返回一个承诺?你可能永远不会兑现这个承诺。 -
如果没有
importAttributeRecord的代码,就不可能准确地说出你做错了什么,因为问题很可能出在那个函数上
标签: javascript ecmascript-6 promise async-await es6-promise