简体   繁体   中英

nodejs binding an object in callback function

Here is what I have tried.

var obj = {sfsf: fsdfs};
connection.query("UPDATE table SET `qty` = `qty` - ? WHERE item_id = ?", [p1, p2], callback.bind(obj))

Callback function:

function callback(f_err, f_rows, f_fields){ //default parameters err, rows, fields
    if(!f_err){
        console.log(obj); //undefined
        // other lines of code
    }
}

I have a doubt that I'm doing it in a wrong way. There are default parameters that get passed after query execution like err, rows, fields . with those parameters, I want to pass some data to the callback function. Is there any other way to do this?

Small citation

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

So, in your case in callback obj bind as this . So you must to change console.log(obj) to console.log(this) . You can find more info at MDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM