使用 async.parallel 处理阵列



我在 Node 中使用异步模块.js,我陷入了从 async.parallel 模块中的全局数组获取值顺序的问题。

function(callback)
{
let array = [url,url,url,url,url,url,url,url,url,url];
async.parallel([
    function(cb){
        //working on one url from array and then remove from array
    },
    function(cb){
        //working on one url from array and then remove from array
    },
    function(cb){
        //working on one url from array and then remove from array
    },
    function(cb){
        //working on one url from array and then remove from array
    },
    function(cb){
        //working on one url from array and then remove from array
    }
],function(error,result){
    if(error)
        callback(error);
    else{
        callback(null,true);
    }   
})
}

async.parallel 的每个内部函数都会调用请求模块来获取另一个 html 页面,并在提取其 url 链接后,再次将这些 url 链接插入到全局数组"array"中。

我不明白我们如何知道哪个函数使用了哪个数组元素?

有两种可能的方法。

一个是你正在做的方式,

async.parallel([
    function(cb){
        //working on one url from array and then remove from array
       arr[0] // 0th here
    },
    function(cb){
        //working on one url from array and then remove from array
          arr[1] // 1st here
    },

....然后你会得到结果[a,b,c,d,e,f]其中a,b,c,d,e,f引用数组中的0th,1st,2nd,3rd,4th元素

另一种方法是通过并行方法的对象而不是数组

async.parallel({
    0: function(cb){
        //working on one url from array and then remove from array
       arr[0] // 0th here
    },
    1: function(cb){
        //working on one url from array and then remove from array
          arr[1] // 1st here
    }
}, function(err, results) {
    // results is now equals to: {0: a, 1: b}
})

最新更新