将对象绑定到Promise.then()参数的正确方法

我发现了一个困难的方法,那就是不能简单地将对象的函数传递给蓝鸟。 我假设蓝鸟then正在做一些魔术,并在匿名函数中包装传递函数。 所以我附加了一个.bind的function,它的工作。 这是与蓝鸟做到这一点的正确方法? 还是有更好的办法?

 var Promise = require("bluebird") var Chair = function(){ this.color = "red" return this } Chair.prototype.build = function(wood){ return this.color + " " + wood } var chair = new Chair() //var x = chair.build("cherry") Promise.resolve("cherry") .then(chair.build.bind(chair)) // color is undefined without bind .then(console.log) 

我知道这一切都不是asynchronous,所以请同步示例,我的用法是asynchronous。

所以我附加了一个.bind的function,它的工作。 这是与蓝鸟做到这一点的正确方法?

是的,这是保留上下文的一种方法。 你也可以传递一个匿名函数(你可能已经知道这一点)。

 Promise.resolve("cherry") .then(function (value) { return chair.build(value); }) .then(console.log); 

还是有更好的办法?

你可以使用蓝鸟的Promise.bind方法,就像这样

 Promise.resolve("cherry") .bind(chair) .then(chair.build) .then(console.log) 

现在,只要Promise处理程序(执行处理程序或拒绝处理程序)被调用,在函数内部, this只会引用chair对象。


注意1:在这个特定的情况下, console.log也把this作为chair对象,但是它仍然可以正常工作,因为在Node.js中, console.log函数不仅定义在原型bu上,还定义在对象本身上,bound到console对象。 相应的代码在这里 。

注2:如果不同的处理程序需要不同的上下文,那么最好编写匿名函数。 在这种情况下, Promise.bind将无济于事。 但是,如果您select使用它,那么您必须为每个处理程序使用不同的上下文,并且您的代码可能看起来像这样

 var chair1 = new Chair("red") var chair2 = new Chair("green") Promise.resolve("cherry") .bind(chair1) // Changing the binding to `chair1` .then(chair1.build) .tap(console.log) .bind(chair2) // Changing the binding to `chair2` .then(chair2.build) .tap(console.log);