2016-04-05 64 views
1

我無法找到答案,儘管它應該是一個相對常見的問題。所有其他問題似乎涉及到簡單地將變量添加到空封閉。如何將ADDITIONAL參數傳遞到現有的回調函數

我有一個回調,它有兩個參數; errdocs,我仍然需要,但也想添加一個額外的數據參數。

db.findOne().exec(function (err, docs) { 
    // err is defined 
    // docs is defined 
}); 

我需要通過與它一起data,所以認爲我能做到這一點:

db.findOne().exec(function (err, docs, data) { 
    // err is defined 
    // docs is defined 
}(data)); 

這是行不通的。所以,我試過如下:

db.findOne().exec(function (err, docs, data) { 
    // err is null 
    // docs is null 
}(null, null, data)); 

這殺死了原始變量errdocs爲好。

那麼,我該如何去做這件事?

+0

'函數(ERR,文檔,數據){'應該返回'內function'作爲'.exec'的處理程序 – Rayon

回答

1

你可以簡單地,只要這個變量是在外部範圍定義使用data變量回調內(只是調用db.findOne()方法之前):

var data = ... 
db.findOne().exec(function (err, docs) { 
    // err is defined 
    // docs is defined 
    // data is defined 
}); 
0

您必須包裝回調函數中的作用。

,如果您有類似的功能:

db.findOne().exec(function (err, docs) { 
    // err is defined 
    // docs is defined 
}); 

你可以用下面的函數來傳遞額外的參數:

db.findOne().exec(function (err, docs) { 
var data={a:'a'}; 
    yourFunction(err, docs, data); 
}); 

function yourFunction(err, docs, data){ 
// access data here 
} 
相關問題