2016-12-29 94 views
0

我google了一些綁定的解釋,但仍然非常困惑。我用以下方式使用承諾綁定。它正在工作,但我不知道爲什麼。希望有人能解釋並幫助我解決我遇到的一個小問題。下面是示例代碼:節點綁定並承諾

var temp1 = function(){ 
    return new Promise(function(resolve, reject){ 
     resolve("hello"); 
    }); 
}; 

var temp2 = function(para1, para2){ 
    console.log("1:", para1); 
    console.log("2:", para2) 
    return new Promise(function(resolve, reject){ 
     resolve(para1+" "+para2); 
    }); 
}; 

temp1().then(temp2.bind(null,"world")).then(function(out){ 
    console.log(out); 
}); 

輸出:

1:世界\ 2:你好\ 世界你好\

我使用 「綁定」,因爲它可以使代碼清理和更容易的錯誤處理,否則我必須使用以下內容:

temp1().then(function(out1){ 
    return temp2(out1, "world").then(function(out2){ 
     console.log(out2); 
    }); 
}); 

除了如何綁定工作,我有以下問題:

temp1().then(temp2.bind(null,/*the second param is a property of the output from temp1*/)).then(function(out){ 
    console.log(out); 
}); 

我知道我可以隨時打破鏈或增加額外鏈,實現它: 例如

temp1().then(function(out1){ 
    return temp2(out1, (out1.length).to_String()).then(function(out2){ 
     console.log(out2); 
    }); 
}); 

但它會真棒不要打破鏈條。所以我的兩個問題:1.如何綁定工作,2.如何保持鏈(也沒有額外的鏈),而我仍然可以訪問之前的輸出的屬性在下一個函數的參數然後。 謝謝!

回答

1

Function.prototype.bind()

的bind()方法創建一個新的功能,調用它時,具有其將此關鍵字設置爲所提供的值,與任何提供前述參數的給定序列,當新功能被稱爲。

從技術上講,temp2.bind(null,"world")將返回一個函數並通過null,"world"作爲參數。然後,這些參數與temp1的結果合併,該索引爲"hello",索引號爲0。因此,傳遞給temp2的實際參數是"hello", "world"

保持環比你可以寫:

temp1() 
    .then(function (out) { 
    return temp2(out,"world") 
    }) 
    .then(function(out){ 
    console.log(out); 
    }); 

這就是爲什麼人們創造的承諾,這樣就可以很好地把它們連。你給出的例子的作品,但它類似於Callback Hell。

+0

因爲根據定義的論點是'任何提供'之前,結果不是「你好」,「世界」,而是「世界「, 「你好」。我仍然不明白爲什麼參數不是'null',但世界「,你好」。初始的null似乎在某處被吃掉。 –

0

bind()用於設置稍後調用的函數的適當上下文。我不認爲你需要在這種情況下使用它。如果你正在使用es6你可以做一些像這樣:

temp1() 
    .then(out1 => temp2(out1, out1.length.toString())) 
    .then(console.log) 
    .catch(console.log); 

它使用一個隱含的回報。這是有效的,因爲temp2()也返回一個promsie,所以我們可以將它鏈接到下一個承諾解析器