gpt4 book ai didi

ecmascript-6 - 如何在 promise 绑定(bind)中使用 ES6 箭头函数 (bluebird)

转载 作者:行者123 更新时间:2023-12-04 05:04:00 24 4
gpt4 key购买 nike

我正在使用 babel 的 require hook在节点中利用 ES6,但我在 bluebird promise 链中遇到了箭头函数的一些挑战。

我在我的 promise 链的顶部使用 .bind({}) 和一个空对象来创建共享状态,我可以在其中存储以前的值,直到我需要它们在链的更下方。 Bluebird 将此用法解释为“useful side purpose”。

当我切换到箭头函数时,我不能再使用共享状态,因为箭头函数使用词法 this,它在 babel 中是 undefined(babel 自动在严格模式下运行) .

工作示例:https://jsbin.com/veboco/edit?html,js,console

ES6 示例(不工作):https://jsbin.com/menivu/edit?html,js,console

在这种情况下有什么方法可以利用箭头函数吗?在我的代码中,我从一个对象方法中调用这些方法 - this 不应该被定义为调用该方法的对象吗?

最佳答案

如果您不想词法绑定(bind) this,则无需使用箭头函数。如果您想要动态绑定(bind)this,只是不要使用箭头函数。

当然,您可以将 .bind({}) 作为一个整体废弃,并通过将所有内容放入对象方法(或示例中的 IIFE)来使用绑定(bind)到对象的箭头函数):

(function() {
this; // the value that everything is bound to
double(2).then(result => {
this.double = result; // store result here
return triple(2);
}).then(result => {
console.log('double:', this.double);
console.log('triple:', result);
console.log('sum:', this.double + result);
}).catch(err => {
console.log(err.message);
});
}.call({}));

但是,有much better ways to access previous results in a promise chaincontextual state , 特别是如果你是 using ES6 !

关于ecmascript-6 - 如何在 promise 绑定(bind)中使用 ES6 箭头函数 (bluebird),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32082265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com