我正在使用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"。
我不知道我们怎么知道哪个函数使用哪个数组元素?
答案 0 :(得分:0)
有两种可能的方法。
一个是你正在做的事,
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}
})