很确定我在这里漏掉了一些小东西。我在对象数组上应用 javascript foreach 循环。通过循环,我正在对 api 进行异步调用以更新数据。我想要的是 foreach 循环,在继续下一次迭代之前等待 promise 得到履行。
这是代码示例
entriesToUpdate.forEach(function (item) {
SomeService.updateEntry(item).then(function (res) {
//Do some stuff here.
});
//Wait for the above promise to be fulfilled before going to next iteration
});
最佳答案
您可以像这样定义一个函数来递归处理条目:
function updateEntries(entries, i) {
if(i < entries.length) {
return SomeService.updateEntry(entries[i]).then(function() {
return updateEntries(entries, i+1);
});
}
}
updateEntries(entriesToUpdate, 0);
或者您可以将您的 promise 串起来。
var promise = SomeService.updateEntry(entriesToUpdate[0]);
for(var i = 1; i < entriesToUpdate.length; i++) {
promise = promise.then(function() {
return SomeService.updateEntry(entriesToUpdate[i]);
});
}
(这些例子可能行不通;我不熟悉 AngularJS promises。只有 ES6 promises)
关于Javascript/Angular : wait for promise to be fulfilled before going to the next iteration in foreach Loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34891323/