async.waterfall绑定上下文

我目前正在与node.js的Web应用程序工作,我不能找出库asynchronous的上下文问题。

这里是我的应用程序的代码的一个例子:

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)的上下文,否则async会改变它。 我知道了。 但是我不明白为什么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”variables,这意味着该函数知道“this”上下文。 但是瀑布调用中的函数不会,即使我将“this”绑定到它们。

我想通过在调用瀑布之前创build一个与'this'等同的'me'variables,并将函数与'me'variables绑定在一起,而不是这个,我想了解一个方法,为什么当我使用async.waterfall而不是当我使用async.parallel时,我被迫做这个。

我希望我能清楚地描述我的问题,如果有人能帮助我理解,那将是一种莫大的快乐!

你遇到的问题与parallel或者瀑布无关,而是在waterfall情况下,你在callbacknotification.db.execute引用了this ,而在parallel情况下,只有一个调用在那里done 。 您可以再次使用bind来绑定该callback:

 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) { //… });