目前,我正在使用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方法来绑定我的对象( 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”上下文。但是瀑布调用内部的函数并不是这样,即使我将“这个”绑定到它们。
我想出了一种方法,通过在调用瀑布之前创建一个等于“this”的'me‘变量,并将函数绑定到'me’变量,而不是这个,但我想了解为什么我在使用async.waterfall时被迫这样做,而不是当我使用async.parallel时。
我希望我能清楚地描述我的问题,如果有人能帮我理解的话,那将是一种极大的荣幸!
发布于 2015-04-20 09:20:18
您所看到的问题与并行或瀑布无关,而是在waterfall情况下如何在回调到notification.db.execute中引用this,而在parallel情况下,那里只有对done的调用。您还可以再次使用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) {
//…
});https://stackoverflow.com/questions/29743682
复制相似问题