我目前正在使用 node.js 开发 Web 应用程序,我无法确定库异步的上下文问题。
这是我的应用程序的代码示例:
notification.prototype.save = function (callback) {
async.parallel([
// Save the notification and associate it with the doodle
function _saveNotification (done) {
var query = 'INSERT INTO notification (notification_id, user_id, doodle_id, schedule_id) values (?, ?, ?, ?)';
notification.db.execute(query, [ this.notification_id, this.user_id, this.doodle_id, this.schedule_id ], { prepare : true }, function (err) {
return done(err);
});
console.log("SAVE NOTIFICATION");
console.log("doodle_id", this.doodle_id);
}.bind(this),
// Save notification for the users with the good profile configuration
function _saveNotificationForUsers (done) {
this.saveNotificationForUsers(done);
}.bind(this)
], function (err) {
return callback(err);
});
};
所以在这段代码中,我必须使用 bind 方法来绑定(bind)我的对象 ( this ) 的上下文,否则异步会更改它。我知道了。 但我不明白的是为什么 this.saveNotificationForUsers 的代码不能以同样的方式工作:
notification.prototype.saveNotificationForUsers = function (callback) {
console.log("SAVE NOTIFICATION FOR USERS");
console.log("doodle id : ", this.doodle_id);
async.waterfall([
// Get the users of the doodle
function _getDoodleUsers (finish) {
var query = 'SELECT user_id FROM users_by_doodle WHERE doodle_id = ?';
notification.db.execute(query, [ this.doodle_id ], { prepare : true }, function (err, result){
if (err || result.rows.length === 0) {
return finish(err);
}
console.log("GET DOODLE USERS");
console.log("doodle id : ", this.doodle_id);
return finish(err, result.rows);
});
}.bind(this)
], function (err) {
return callback(err);
});
};
当我调用前面的代码时,第一个 console.log 能够向我显示“this.doodle_id”变量,这意味着该函数知道“this”上下文。 但是 waterfall 调用中的函数不会,即使我将“this”绑定(bind)到它们也是如此。
我想出了一种方法来使其工作,方法是在我调用 waterfall 之前创建一个等于“this”的“我”变量,并将函数与“我”变量绑定(bind),而不是这个,但我会想了解为什么我在使用 async.waterfall 时被迫这样做,而不是在使用 async.parallel 时。
我希望我对我的问题的描述是清楚的,如果有人能帮助我理解,我将非常高兴!
最佳答案
您看到的问题与并行或 waterfall 无关,而是在 waterfall
情况下,您如何在回调中引用 this
notification.db.execute
,而在 parallel
的情况下,那里只有对 done
的调用。您也可以再次使用 bind
来绑定(bind)该回调:
async.waterfall([
function _getDoodleUsers (finish) {
//…
notification.db.execute(query, [ this.doodle_id ], { prepare : true }, function (err, result){
//…
}.bind(this)); // <- this line
}.bind(this)
], function (err) {
//…
});
关于javascript - async.waterfall 绑定(bind)上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29743682/