遍历数组在每个元素上运行异步任务 [英] Iterate over array running async task on each element

查看:162
本文介绍了遍历数组在每个元素上运行异步任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目列表,我想在每个项目上运行一个异步任务.

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:

http://jsfiddle.net/8A8CG/

或者,如果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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆