如何在数组的 forEach 循环中使用 promise 来填充对象 [英] How to use promise in forEach loop of array to populate an object
问题描述
我正在一个数组上运行一个 forEach 循环并进行两次返回承诺的调用,我想填充一个对象说 this.options
,然后用它做其他事情.现在,如果我使用以下代码示例并首先进入 then 函数,我就会遇到异步问题.
I am running a forEach loop on an array and making two calls which return promises, and I want to populate an object say this.options
, and then do other stuff with it. Right now I am running into the async issue if i use the following code sample and i get into the then function first.
$.when.apply($, someArray.map(function(item) {
return $.ajax({...}).then(function(data){...});
})).then(function() {
// all ajax calls done now
});
这是下面的工作代码,但它仅适用于数组中的第一个元素,因为我在响应的 .then
中调用了结果函数.我想先对数组的所有元素进行所有的提取,然后调用结果函数来做某事.
This is working code below, but it only works for the first element in the array, because I call the resulting function in the .then
of the response. I want to do all the fetch first for all elements of the array and then call the resulting function to do something.
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 对象调用结果函数?
How do i populate the self.files
object after the forEach loop is complete, and then call the resulting function with the files object?
推荐答案
Promise.all()
在这里会有帮助:
var promises = [];
array.forEach(function(element) {
promises.push(
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
});
}).catch ((error) = > {
console.log('Error: ', error);
})
);
});
Promise.all(promises).then(() =>
self.resultingFunction(self.files)
);
这会为每个项目启动 AJAX 调用,一旦调用完成,将每次调用的结果添加到 self.files
并调用 self.resultingFunction()
在完成所有调用之后.
This starts the AJAX call for each of the items, adds the result of each call to self.files
once the call is complete and calls self.resultingFunction()
after all calls have been completed.
根据 Yury Tarabanko 的建议进行了简化.
Simplified based on Yury Tarabanko's suggestions.
这篇关于如何在数组的 forEach 循环中使用 promise 来填充对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!