跳至內容

unicorn/no-single-promise-in-promise-methods 正確性

此規則預設開啟。
🛠️ 此規則的部分違規行為可自動修復。

作用

禁止將單一元素陣列傳遞給 Promise 方法

為何不好?

將單一元素陣列傳遞給 Promise.all()Promise.any()Promise.race() 很可能是一個錯誤。

範例

此規則的 不正確 程式碼範例

javascript
async function bad() {
  const foo = await Promise.all([promise]);
  const foo = await Promise.any([promise]);
  const foo = await Promise.race([promise]);
  const promise = Promise.all([nonPromise]);
}

此規則的 正確 程式碼範例

javascript
async function good() {
  const foo = await promise;
  const promise = Promise.resolve(nonPromise);
  const foo = await Promise.all(promises);
  const foo = await Promise.any([promise, anotherPromise]);
  const [{ value: foo, reason: error }] = await Promise.allSettled([promise]);
}

參考資料

根據 MIT 許可發布。