2016-05-12 72 views
4

我在具有相同回調函數 的兩個函數中使用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......} 

Q:如何可在onefunctionsecondfunctionthirdfunction訪問TESTUSER值。

現在我得到undefined err。我也嘗試了正常參數傳遞邏輯onefunction(testuser),但它不工作。

我想在多種情況下使用onefunctiontwofunction ......我該怎麼做?

+0

使它的功能的參數,並把它傳遞給它們。 –

+0

@FelixKling你可以簡單解釋一下嗎?你的意思是說'onefunction(testuser)' –

+1

那麼,你也必須通過'回調'我假設。因爲你必須將函數傳遞給'async.parallel'(所以看起來),它應該是'callback => onefunction(testuser,callback)'等。 –

回答

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......} 
-2

這是我怎麼能在onefunctionsecondfunction &等訪問testuser值..
代碼:

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); 
} 
+0

這是如何解決OP問題的? –

+0

'callback => onefunction(testuser,callback)'此代碼正在爲我工​​作..感謝amol的嘗試 –

+0

@PrashantTapase:您可以在此發佈自己的答案(&接受它),以便它也可以幫助其他人。謝謝:) –