将变量传递到回调函数中

Passing variables into callback function

本文关键字:回调 函数 变量      更新时间:2023-09-26

我有一段这样的代码:

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作为全局变量。

有可能在checkExistence()获得guid吗?

可以将 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));

你可以使用 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));

也许你可以使用绑定函数,

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

并像这样调用方法查询

con.query('SELECT guid FROM myDB.myTable WHERE guid = ?', guid, checkExistence.bind(null, guid);
    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));