2017-06-21 58 views
0

鑑於我創建myPromise。 它解析時會返回另一個promise我可以控制由then()方法返回的承諾的方式解決

let myPromise = new Promise((resolve: Function, reject: Function) => { 
    setTimeout(() => { 
     resolve('my promise resolved after 2 seconds'); 
    }, 2000); 
}) 


myPromise.then(value => { 
    console.log(value); 
}).then((value) => { 
    // how can I make the promise returned by myPromise.then() 
    //resolve in a specific way ? 
}) 

我如何控制promise通過myPromise.then()做出決議回的方式嗎?

+0

我不明白這個問題。當調用'then'函數時,promise已經解決。 – evolutionxbox

+0

你能重新表達你的問題嗎?這很難理解 – dloeda

+0

*返回值*,將值傳遞給下一個然後OR *返回新的Promise *等待新的Promise,然後接下來是它的結果 –

回答

0

裏面一個.then()處理程序中,你有三個選擇,都會影響返回的承諾那.then()電話(我將它稱爲「父母」承諾)。

  1. 返回一個值。當您從.then()處理程序返回值時,該值將成爲最初調用.then()時返回的承諾的已解析值。

  2. 返回承諾。當您從.then()處理程序返回承諾時,它將鏈接到父承諾,父承諾將「遵循」新承諾(resolve/value,reject/reason)。

  3. 拋出異常。這將導致父承諾被拒絕,異常成爲拒絕原因。

如果返回從.then()處理程序是一樣的return undefined所以它只是設置解析值到undefined(與返回的undefined的值)沒有。


這個結構告訴你:

myPromise.then(value => { 
    console.log(value); 
}).then((value) => { 
    // how can I make the promise returned by myPromise.then() 
    //resolve in a specific way ? 
}); 

是麻煩,因爲第一.then()處理程序沒有返回。這與返回undefined相同,因此第二個value始終爲undefined,因此無用。如果您有第一個.then()處理程序的實際原因,您可以通過如下方式保留期望值:

myPromise.then(value => { 
    console.log(value); 
    return value; 
}).then((value) => { 
    // how can I make the promise returned by myPromise.then() 
    //resolve in a specific way ? 
}); 
0

如果你不需要做一些其他的異步操作,只是返回值:

myPromise.then(value => { 
    return value; 
}).then((value) => { 
    // ... 
}) 

但我不知道你爲什麼會做這個,考慮到你可能只是刪除第一個.then並在第二個.then做所有事情。

如果您需要做的另一個異步操作,你可以返回一個新的承諾,當你需要解決它:

myPromise.then(value => { 
    // Do some other async operation. I am explicitly creating the promise 
    // here inline to be clear. In real code, you'd probably want to wrap this 
    // in another function. 
    return new Promise((resolve: Function, reject: Function) => { 
     resolve(value); 
    }); 
}).then((value) => { 
    // ... 
}) 
+0

爲什麼不返回值; ? –

+0

你可以這樣做,但問題已經基本上用第二個'.then'來做了。所以我假設他們想在第二個'.then'之前做其他異步操作。 –

+0

第二部分是反模式。根本沒有必要創建一個新的'Promise'。 –

相關問題