将变量传递给回调函数

时间:2016-02-18 10:54:16

标签: javascript node.js callback

我有一段这样的代码:

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

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

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);

con是从node-mysql

创建的连接

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

是否可以在guid中获得checkExistence()

4 个答案:

答案 0 :(得分: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));

答案 1 :(得分:0)

您可以使用Function.bind函数,如下所示:

var checkExistence = function(guid, 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.bind(null, guid));

答案 2 :(得分:0)

也许你可以使用绑定功能,

var checkExistence = function(guid, err, rows) { ...

并像这样调用方法查询

con.query('SELECT guid FROM myDB.myTable WHERE guid = ?', guid, checkExistence.bind(null, guid);

答案 3 :(得分:0)

    var checkExistence = function(err, rows, guid) {
    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(err, rows, guid));