簡體   English   中英

當我 add.catch 時,promise 是否已解決?

[英]Is a promise resolved when I add .catch to it?

我是 typescript / javascript 的新手,所以我對承諾不太了解。 這是我的用例:我在我的雲函數中創建三個不同的 promise,然后使用Promise.all([promise1, promise2, promise3]). 這些承諾中的每一個都是在 function 中創建的,帶有“return Promise ...”。

我的問題是,當我在這些函數中添加“.catch”時, Promise.all仍然有效? 使用和不.catch()返回someServiceThatCreatesPromise()有什么區別嗎?

代碼

export async function myCloudFirestoreFunction() {
   try  {
        const myFirstPromise = createFirstPromise()
        const mySecondPromise = createSecondPromise()
        const thirdPromise = createThirdPromise()

        return Promise.all([
          myFirstPromise,
          mySecondPromise,
          myThirdPromise
       ]);
   } catch (err) {
       functions.logger.err(`Something bad happened, See: ${(err as Error).message}`
   }
}

// Difference with and without `.catch`?
function createFirstPromise() {
   return someServiceThatCreatesPromise().catch((err) => { // LOGGING });
}

// Difference with and without `.catch`?
function createSecondPromise() {
   return someServiceThatCreatesPromise().catch((err) => { // LOGGING });
}

// Difference with and without `.catch`?
function createThirdPromise() {
   return someServiceThatCreatesPromise().catch((err) => { // LOGGING });
}

假設您的所有Promise都解決並且不拒絕,那么在createNPromise中添加.catch不會影響任何事情。

但是,如果Promise之一拒絕並且您在.catch方法中捕獲它,那么它將無法按預期工作,除非您重新拋出該錯誤並在myCloudFirestoreFunction function 中的try/catch中再次捕獲它.

 async function myCloudFirestoreFunction() { try { const result = await Promise.all([ createFirstPromise(), createSecondPromise() ]); } catch (error) { console.log({ error }); } } function createFirstPromise() { return Promise.reject("Oof").catch((e) => { // do work, eg log, then // pass the error forward so that it can be caught // inside the caller throw e; }); } function createSecondPromise() { return Promise.resolve("value"); } myCloudFirestoreFunction();

或者,您只需在調用者 ( myCloudFirestoreFunction ) 中catch錯誤,而不是單獨捕獲它們。

 async function myCloudFirestoreFunction() { const result = await Promise.all([ createFirstPromise(), createSecondPromise() ]).catch((err) => console.log({ err })); } function createFirstPromise() { return Promise.reject("Oof"); } function createSecondPromise() { return Promise.resolve("value"); } myCloudFirestoreFunction();

當我在這些函數中添加“.catch”時,Promise.all 還能工作嗎?

在 promise 上調用catch()不會以任何方式改變原始 promise 的工作方式。 它只是附加一個回調,當第一個 promise 被拒絕時調用,並且還返回另一個 promise 在原始 promise 被滿足或拒絕后解析。

使用和不使用.catch() 返回 someServiceThatCreatesPromise() 有什么不同嗎?

它不會對依賴於返回的 promise 的代碼產生任何影響。 原始的 promise 和catch()返回的都將在原始工作完成時告訴下游代碼。

我建議閱讀有關 Promise 的綜合文檔,例如:

那里有一個圖表,您可以按照該圖表了解每個轉彎處發生的情況。 同樣在該文檔中,您將閱讀:

即使 a.then() 缺少返回 Promise object 的回調 function ,處理也會繼續到鏈的下一個環節。 因此,一個鏈可以安全地省略每個拒絕回調 function 直到 final.catch()。

暫無
暫無

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

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