async.waterfall 绑定上下文

async.waterfall bind context

我目前正在使用 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' 绑定到它们。

我想出了一种方法来使其工作,方法是在我调用瀑布之前创建一个等于 'this' juste 的 'me' 变量,并通过将函数与 'me' 变量绑定' 而不是这个,但我想了解为什么当我使用 async.waterfall 而不是当我使用 async.parallel.

时我被迫这样做

我希望我的问题描述清楚,如果有人能帮助我理解,我将非常高兴!

您看到的问题与并行或瀑布无关,而是在 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) {
    //…
});