簡體   English   中英

關於在 firebase 雲函數中 promise 的 then 回調中返回 null 值的問題

[英]Question regarding returning a null value in a then callback of a promise in firebase cloud functions

所以在我的雲 function 中,我有這段代碼:

return users_pending_update.once('value').then((snapshot) => {
    if (snapshot.exists()) {
        return manage(ref_date, zonesYetToBeUpdated, snapshot);
    } else {
        return users_tzs_ref.once('value').then((snapshot) => {
            if (snapshot.exists()) {
                return manage(ref_date, zonesYetToBeUpdated, snapshot);
            } else {
                return null;
            }
        }).catch((error) => {
            console.error("Getting the list of values from the \"users_tzs\" node failed with error: " + error);
        });
    }
}).catch((error) => {
    console.error("Getting the list of values from the \"users_pending_update\" node failed with error: " + error);
});

我的問題是關於您可以在代碼中看到的return null語句。 我擁有它的唯一原因是因為我收到警告,並非所有代碼路徑都返回值。 我不需要也不關心那邊的那條路。 如果我使用return Promise.reject("text") 之類的東西,警告也會消失。 如果我將它保留為return null會有問題嗎?如果是,我應該將其更改為什么?

如果我將它保留為 return null 會有問題嗎?如果是,我應該將其更改為什么?

這實際上取決於調用者的邏輯或您希望調用者的邏輯是什么。 當您return null; 在那里,你是說在這個特定的代碼路徑中,你希望你從這個 function 返回的 promise 的解析值是null 如果:

  • 調用者根本沒有使用解析值,這是 function 的類型,對調用者來說真正重要的是操作成功或出錯時,並且沒有特定有用的解析值。
  • 調用者正在檢查null或其他一些虛假值的解析值並相應地采取行動。 例如,如果您查詢某些內容但未找到任何結果,某些數據庫接口將返回類似null的內容。 這不是錯誤情況,它只是通知您沒有找到搜索結果。

至於更改為return Promise.reject("text")類的內容,會產生完全不同的結果。 這使得此特定代碼路徑拒絕它返回的 promise,這將為調用者生成截然不同的行為。 您通常只會在這是錯誤情況時才這樣做,並且您希望將此類錯誤傳達回調用者並且您希望他們在.catch() try/catch (if using await`)。

此外,您通常不會拒絕字符串。 通常您拒絕並返回Error object。

暫無
暫無

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

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