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

Tho*_*ggi 24 javascript this node.js promise bluebird

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

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)
Run Code Online (Sandbox Code Playgroud)

我知道这些都不是异步的,所以请使用同步示例,我的用法是异步.

the*_*eye 24

所以我附加了一个.bind函数,它工作.这是用蓝鸟做这个的正确方法吗?

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

Promise.resolve("cherry")
    .then(function (value) {
        return chair.build(value);
    })
    .then(console.log);
Run Code Online (Sandbox Code Playgroud)

还是有更好的方法吗?

你可以实际使用bluebird的Promise.bind方法,就像这样

Promise.resolve("cherry")
  .bind(chair)
  .then(chair.build)
  .then(console.log)
Run Code Online (Sandbox Code Playgroud)

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


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

注意2:如果不同的处理程序需要不同的上下文,那么最好编写匿名函数.在那种情况下,Promise.bind不会有太大帮助.但是如果你选择使用它,那么你必须为每个处理程序使用不同的上下文,你的代码可能看起来像这样

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);
Run Code Online (Sandbox Code Playgroud)