Bluebird 的绑定方法在调用之间保存上下文(this)
bind method from Bluebird saves context(this) between calls
在这个文档之后 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 }
这是正确的行为还是我在某处弄错了?
Bluebird Promise.bind
被误用。它应该与动态 this
:
一起使用
Without arrow functions that provide lexical this, the correspondence between async and sync code breaks down when writing object-oriented code. .bind alleviates this.
例如:
promise.bind({})
.then(function () {
console.log('this', callNumber, this);
this.t = 1
})
对于箭头函数,this
是词法的,指的是 Node 模块,module.exports
。它在 chain
个调用之间保持不变。
在这个文档之后 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 }
这是正确的行为还是我在某处弄错了?
Bluebird Promise.bind
被误用。它应该与动态 this
:
Without arrow functions that provide lexical this, the correspondence between async and sync code breaks down when writing object-oriented code. .bind alleviates this.
例如:
promise.bind({})
.then(function () {
console.log('this', callNumber, this);
this.t = 1
})
对于箭头函数,this
是词法的,指的是 Node 模块,module.exports
。它在 chain
个调用之间保持不变。