簡體   English   中英

異步 promise 執行函數

[英]Async promise executor functions

我有一個 function 返回一個 Promise 這樣的:

async function processFolder(folder) {
    return new Promise(async (res) => {
        const table = {};
        const list = await getHTMLlist(folder);
        if (list.length === 0) res(table);
        for (let i = 0; i < list.length; i++) {
            await processFile(folder, list[i], table);
        }
        res(table);
    });
}

我正在使用警告我的 ESLint:

Promise executor functions should not be async ” 這是no-async-promise-executor規則,由於 Promise 聲明中的 async 關鍵字而引發錯誤。

我已經在代碼的其他部分修復了相同的問題,其中 Promise 中只有一個 await 使用 ESLint 文檔這一頁上建議的技術並顯示在這個答案中,但在我的用例中我真的不知道如何重構代碼以避免該錯誤。 歡迎任何建議

您不需要自己創建一個新的 promise,因為async函數總是返回 promise。如果async function 的返回值不是 promise,則它會隱式包裝在 promise 中。

因此,您需要刪除創建新的 promise 實例的代碼,執行程序 function 中的代碼應該位於processFolder function 的頂層。

您的代碼可以簡化如下所示:

async function processFolder(folder) {
    const table = {};
    const list = await getHTMLlist(folder);

    if (list.length > 0) {
       for (let i = 0; i < list.length; i++) {
           await processFile(folder, list[i], table);
       }
    }

    return table;
}

理想情況下,您還應該將processFolder function 內的代碼包裝在try-catch塊中,以捕獲和處理在執行此 function 期間可能發生的任何錯誤。

暫無
暫無

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

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