遍历数组在每个元素上运行异步任务 [英] Iterate over array running async task on each element
问题描述
我有一个项目列表,我想在每个项目上运行一个异步任务.
I have a list of items, which I want to run an async task on each.
我想进行同步,以便在前一个元素完成后将处理每个元素.到目前为止,我尝试过的是:
I want to synchronize so each element will be processed once the preceding element has completed. What I've tried so far is:
function processItems(items) {
var i = 0;
while(i < items.length) {
asyncFunc(items[i], function() { i++ }); // asyncFunc takes a callback parameter
}
}
但是这会永远循环(我相信i
在回调函数中超出范围).
However this loops forever (I believe i
is out of scope in the callback function).
有没有更好的方法来实现这一目标?
Is there a better way to achieve this?
推荐答案
我认为以下内容可以满足您的需求:
I think the following accomplishes what you're looking for:
function processItems(items) {
var i = 0,
length = items.length,
fn = function() {
if(i < length) {
asyncFunc(items[i], fn);
i++;
}
};
fn();
}
fn
是一个函数,只要索引小于长度,就会将回调设置为等于自身.然后,我一次调用fn
将其启动.这是一个小提琴:
fn
is a function that sets the callback equal to itself as long as the index is less than the length. Then I call fn
once to start it off. Here's a fiddle:
或者,如果asyncFunc
返回承诺,您可以使用
Alternatively, if asyncFunc
returns a promise, you can use Array#reduce
to process the items in a series:
function processItems(items) {
return items.reduce((promise, item) => {
return promise.then(() => asyncFunc(item));
}, Promise.resolve());
}
这篇关于遍历数组在每个元素上运行异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!