[英]promise Q not working consistently
我正在使用promise的Q庫,我有一個基本的問題我已經創建了此代碼,當我省略第一個返回Q字時,我得到了錯誤(返回Q(100)),但是對於第二個和第三個,則沒有如果我忽略它們,問題仍然存在,為什么?
function firstFn() {
return Q(100);
};
function secFn(){
return Q(200);
};
function thirdFn(){
return q(300);
};
firstFn().then(function(a){
alert(a);
return secFn();
}).then(function(b){
alert(b);
return thirdFn();
}).then(function(c){
alert(c)
});
您正在對從firstFn返回的值調用.then(function(a)...),因此它需要返回上面帶有.then函數的內容。
對於其他兩個函數,您正在Q .then()回調中調用它們。 如果您從這些回調中返回承諾,則Q將利用它們,但如果您不返回任何內容,則Q也可以。
詳細闡述羅伯特·利維說的話:
Promises / A +規范指定了Q的工作方式,該規范規定,只要從.then
回調返回值.then
就將其作為承諾進行包裝。
調用Q(foo)
所做的與Promise.resolve(foo)
所做的相似,是將事物包裝為一個承諾。 因此Q(100)是對值100的承諾。每當從then
回調返回一個值時,它都會被“包裝”。
Q(100);
Q().then(function(){ return 100; }); // the same as the line above
Q.try(function(){ return 100; }); // same as line above
// or in ES6 native promises or bluebird promises
Promise.resolve(100);
Promise.resolve().then(function(){ return 100; }); // the same as the line above
明確地說,該規范說明了.then
回調參數:
如果
onFulfilled
或onRejected
返回值x,請運行Promise Resolution Procedure [[Resolve]](promise2,x)。
承諾解決程序指出:
如果x是一個承諾,則采用其狀態[3.4] :(請注意:不是我們的情況)
否則,如果x是對象或函數,
then
讓x.then
。 [3.5]如果
then
不是函數,則用x履行承諾
因此,Q這樣做是可以的,這使我們的生活更輕松,並使我們能夠像承諾一樣吸收價值。 原因是我們希望保持.then
鏈的外觀異步,因此返回值實際上只是在履行我們包裝的新承諾
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.