【发布时间】:2015-09-09 21:29:05
【问题描述】:
我发现很难将对象的函数简单地传递给 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)
我知道这些都不是异步的,所以请以同步示例为例,我的用法是异步的。
【问题讨论】:
-
没听说过 Bluebird,但是如果它的 Promise 遵循 jQuery 实现的 Promise 模式,那么只要你的目标是支持
Function.bind的现代浏览器,这就是可行的方法(否则你需要自己滚动,或者使用下划线作为bindshim) -
当然。如果@thefourtheye 是对的,并且这个
Promise有它自己的bind功能,我可能会改用它。 -
@Lambat 它是蓝鸟特有的功能:-)
标签: javascript node.js promise this bluebird