什么是在数组(或objs)上迭代异步的最聪明/最干净的方法? [英] Whats the smartest / cleanest way to iterate async over arrays (or objs)?

查看:144
本文介绍了什么是在数组(或objs)上迭代异步的最聪明/最干净的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是怎么做到的:

function processArray(array, index, callback) {
    processItem(array[index], function(){
        if(++index === array.length) {
            callback();
            return;
        }
        processArray(array, index, callback);
    });
};

function processItem(item, callback) {
    // do some ajax (browser) or request (node) stuff here

    // when done
    callback();
}

var arr = ["url1", "url2", "url3"];

processArray(arr, 0, function(){
    console.log("done");
});

有什么好处吗?如何避免那些意大利面条的代码?

Is it any good? How to avoid those spaghetti'ish code?

推荐答案

查看 async 库,它是为控制流(异步的东西)而制作的,它有很多用于数组的方法:each,filter,map。查看github上的文档。以下是您可能需要的内容:

Checkout the async library, it's made for control flow (async stuff) and it has a lot of methods for array stuff: each, filter, map. Check the documentation on github. Here's what you probably need:

每个(arr,迭代器,回调)

并行地对数组中的每个项应用迭代器函数。使用列表中的项目调用迭代器,并在完成时调用它。如果迭代器将错误传递给此回调,则会立即调用每个函数的主回调并显示错误。

Applies an iterator function to each item in an array, in parallel. The iterator is called with an item from the list and a callback for when it has finished. If the iterator passes an error to this callback, the main callback for the each function is immediately called with the error.

eachSeries(arr,迭代器,回调)

仅与相同迭代器将串行应用于数组中的每个项目。只有当前的迭代器完成处理后才会调用下一个迭代器。这意味着迭代器函数将按顺序完成。

The same as each only the iterator is applied to each item in the array in series. The next iterator is only called once the current one has completed processing. This means the iterator functions will complete in order.

这篇关于什么是在数组(或objs)上迭代异步的最聪明/最干净的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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