将变量传递给回调函数

Bri*_*ian 1 javascript callback node.js

我有一段这样的代码:

var guid = 'unique_guid';
con.query('SELECT guid FROM myDB.myTable WHERE guid = ?', guid, function(err, rows) {
    if(err) throw err;
    if(rows.length == 0) {
        console.log('new guid: ' + guid);
        // do more things which require guid
    } else {
        console.log('old guid: ' + guid);
        // do more things which require guid
    }
}
Run Code Online (Sandbox Code Playgroud)

为了避免回调地狱,我给回调函数一个名称,并将其重构为如下:

var checkExistence = function(err, rows) {
    if(err) throw err;
    if(rows.length == 0) {
        console.log('new guid: ' + guid);       // guid can't be referenced here
        // do more things which require guid
    } else {
        console.log('old guid: ' + guid);       // guid can't be referenced here
        // do more things which require guid
    }
}
con.query('SELECT guid FROM myDB.myTable WHERE guid = ?', guid, checkExistence);
Run Code Online (Sandbox Code Playgroud)

con是从node-mysql创建的连接

现在我的问题是我无法引用guid checkExistence(),并且我不想将其guid作为全局变量.

是否有可能得到guidcheckExistence()

jcu*_*bic 6

您可以添加guid作为参数并返回一个函数:

var checkExistence = function(guid) {
    return function(err, rows) {
        if(err) throw err;
        if(rows.length == 0) {
            console.log('new guid: ' + guid);       // guid can't be referenced here
            // do more things which require guid
        } else {
            console.log('old guid: ' + guid);       // guid can't be referenced here
            // do more things which require guid
        }
    };
};
con.query('SELECT guid FROM myDB.myTable WHERE guid = ?', guid, checkExistence(guid));
Run Code Online (Sandbox Code Playgroud)