我在具有相同回调函数的两个函数中使用async.parallel
。在第二个函数(two()
)中添加第三个函数作为加法函数
function one(){
var testuser = 1;
async.parallel([onefunction, secondfunction], function(err, result){...})
}
function two(){
var testuser = 2;
async.parallel([onefunction, secondfunction, thirdfunction], function(err, result){...})
}
function onefunction(callback){....code with testuser......}
function twofunction(callback){....code with testuser......}
function thirdfunction(callback){....code with testuser......}
问:如何在onefunction
,secondfunction
和thirdfunction
中访问testuser值。
现在我得到 undefined err 。我也试过普通的参数传递逻辑onefunction(testuser)
,但它没有用。
我想在多个案例中使用onefunction
,twofunction
......我该怎么做?
答案 0 :(得分:0)
正如@Felix建议的那样,
function one(){
var testuser = 1;
async.parallel([onefunction, secondfunction], function(err, result){...})
}
function two(){
var testuser = 2;
async.parallel([
callback => onefunction(testuser, callback),
callback => twofunction(testuser, callback),
callback => thirdfunction(testuser, callback)], function(err, result){...})
}
function onefunction(callback){....code with testuser......}
function twofunction(callback){....code with testuser......}
function thirdfunction(callback){....code with testuser......}
答案 1 :(得分:-2)
这是我如何在testuser
,onefunction
&中访问secondfunction
值的方法。等......
的代码:强>
var async = require('async');
function one(){
var testuser = 1;
//You can bind a context here; remember to pass the context i.e. null for this, otherwise it won't work as expected.
async.parallel({one_func:onefunction.bind(null,testuser), two_func:twofunction.bind(null,testuser)}, function(err, result){
console.log("In one()");
console.log("err",err);
console.log("result",result); //result array with all task's results e.g. one_func, two_func
console.log("testuser",testuser);
})
}
function onefunction(testuser,cb){
console.log('onefunction');
return cb(null,{"testuser":testuser});
}
function twofunction(testuser,cb){
console.log('twofunction');
return cb(null,{"testuser":testuser});
}
one();
更新:在标题中回答您关于重复使用回调的问题。
您可以重用命名函数作为回调吗?
示例代码:
function one(){
var testuser = 1;
async.parallel({one_func:onefunction.bind(null,testuser), two_func:twofunction.bind(null,testuser)},calback)
}
function calback (err, result){
console.log("calback"); //You can reuse this named function as callbacks
console.log("err",err);
console.log("result",result);
}