簡體   English   中英

如何在鏈的早期解決承諾?

[英]How can I resolve a Promise early in the chain?

我在做一些的Node.js HTTP調用,並要檢查的請求是否失敗或不-我的意思是,一個錯誤不一定認為是“失敗的情況”,但我想執行一些業務邏輯基於此。 我有一些類似於以下代碼的內容(盡管顯然是人為的,因為我簡化了它):

let p = new Promise(function(resolve, reject) {
    // In the real implementation this would make an HTTP request.
    // The Promise resolution is either a response object or an Error passed to the `error` event.
    // The error doesn't reject because the value I'm actually interested in getting is not the response, but whether the HTTP call succeeded or not.
    Math.random() <= 0.5 ? resolve({ statusCode: 200 }) : resolve(new Error());
});

p.then(ret => { if (ret instanceof Error) return false; }) // This line should resolve the promise
 .then(/* Handle HTTP call success */);

基本上,我想說:“如果我解決了一個錯誤對象,請紓困並返回false 。否則,在響應對象上聲明更多內容,然后返回true ,也許返回false 。”

我該如何盡早兌現承諾,而不執行其余的鏈條? 我在想這一切錯嗎? 如果HTTP調用發生錯誤,我不會拒絕承諾,因為AFAICT不能像.catch().catch()獲得值(此承諾最終會傳遞給Promise.all .then() ,但我可能是錯的。

我在FWIW的Bluebird上,所以可以隨意使用其中的多余內容。

您可以從catch()獲取值,只需將其返回即可, 如docs所述

通過不返回拒絕的值或從捕獲中拋出,您可以“從失敗中恢復”並繼續執行鏈

那將是最好的實現;)

只是這里不使用鏈,而只使用一個處理程序:

p.then(ret => {
    if (ret instanceof Error) return false; // This line will resolve the promise
    /* else handle HTTP call success, and return true/false or another promise for it */
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM