【问题标题】:bind method from Bluebird saves context(this) between callsBluebird 的 bind 方法在调用之间保存上下文(this)
【发布时间】:2019-05-07 02:07:55
【问题描述】:

在此文档之后 http://bluebirdjs.com/docs/api/promise.bind.html 我希望 绑定上下文的生命将在调用结束时结束。但显然不是。
以下代码:

const Promise = require('bluebird');

const chain = (callNumber) => {
    console.log('call:', callNumber, '============');
    return asyncFunction()
        .bind({})
        .then(() => {
            console.log('this', callNumber, this);
            this.t = 1
        })
        .then(() => {
            this.t2 = 2
        })
        .then(() => {
            console.log('this', callNumber, this);
        })
};

const asyncFunction = () => new Promise((resolve) => {
    return Promise.delay(100)
        .then(resolve);
});

chain(1).then(() => chain(2));

产生这个结果:

call: 1 ============
this 1 {}
this 1 { t: 1, t2: 2 }
call: 2 ============
this 2 { t: 1, t2: 2 }
this 2 { t: 1, t2: 2 }

预期结果:

call: 1 ============
this 1 {}
this 1 { t: 1, t2: 2 }
call: 2 ============
this 2 {}
this 2 { t: 1, t2: 2 }

这是正确的行为还是我在某处犯了错误?

【问题讨论】:

  • 请按照您的要求添加结果
  • .bind 不适用于箭头函数——它们有词法 this

标签: javascript node.js promise bluebird


【解决方案1】:

Bluebird Promise.bind 被滥用。它应该与动态this一起使用:

如果没有提供词法 this 的箭头函数,在编写面向对象的代码时,异步代码和同步代码之间的对应关系就会崩溃。 .bind 缓解了这种情况。

例如:

promise.bind({})
.then(function () {
    console.log('this', callNumber, this);
    this.t = 1
})

对于箭头函数,this 是词法,指的是 Node 模块,module.exports。在chain 调用之间保持不变。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-12
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多