2015-06-23 50 views
19

我發現了一種難以實現的方式,那就是不能簡單地將對象的函數傳遞給Bluebird then。我假設Bluebird的then正在做一些魔術,並將匿名函數中的傳入函數封裝起來。所以我附加了一個.bind的功能,它的工作。這是藍鳥做這件事的正確方法嗎?或者有更好的方法嗎?將對象綁定到Promise.then()參數的正確方法

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) 

我知道這一切都不是異步,所以請裸露與同步的例子,我的用法是異步的。

+0

有沒有聽說過藍鳥的,但如果它的承諾遵循由jQuery實現的Promise模式,那麼這是一條路,只要你的目標是支持'Function.bind'的現代瀏覽器(否則你需要自己推出,或者使用Underscore作爲'綁定'shim) – Lambart

+0

當然。如果@thefourtheye是對的,並且這個'Promise'有它自己的'bind'功能,那麼我可能會使用它。 – Lambart

+0

@Lambart它是藍鳥特有的功能:-) – thefourtheye

回答

22

所以我附加了一個.bind的功能,它的工作。這是藍鳥做這件事的正確方法嗎?

是的,那是保留上下文的一種方法。你也可以傳遞一個匿名函數(你可能已經知道這一點)。

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) 

現在,每當無極處理器(履行處理或拒絕處理程序)調用,在函數內部,this將僅僅指的chair對象。


注1:在這個特定的情況下,console.log也得到thischair對象,但它仍然能正常工作,因爲在Node.js的,console.log函數的定義,不僅在原型BU也對象本身綁定到console對象。相應的代碼是here

注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); 

相關問題