【发布时间】:2016-11-16 15:56:26
【问题描述】:
我在一个数组上运行一个 forEach 循环并进行两次返回承诺的调用,我想填充一个对象,比如this.options,然后用它做其他事情。现在,如果我使用以下代码示例并首先进入 then 函数,我会遇到异步问题。
$.when.apply($, someArray.map(function(item) {
return $.ajax({...}).then(function(data){...});
})).then(function() {
// all ajax calls done now
});
这是下面的工作代码,但它仅适用于数组中的第一个元素,因为我在响应的 .then 中调用了结果函数。我想先对数组的所有元素进行所有提取,然后调用结果函数来做某事。
array.forEach(function(element) {
return developer.getResources(element)
.then((data) = > {
name = data.items[0];
return developer.getResourceContent(element, file);
})
.then((response) = > {
fileContent = atob(response.content);
self.files.push({
fileName: fileName,
fileType: fileType,
content: fileContent
});
self.resultingFunction(self.files)
}).catch ((error) = > {
console.log('Error: ', error);
})
});
如何在 forEach 循环完成后填充 self.files 对象,然后使用 files 对象调用生成的函数?
【问题讨论】:
-
当您明确需要
map时,为什么还要forEach? -
@YuryTarabanko 我用了一张地图,但也没有用。我也尝试了答案中的方法,但使用了
$.when.apply($, promises).then(),但也没有用。我认为它不起作用,因为我没有按照 ES6 的方式来做。
标签: javascript arrays foreach promise es6-promise