4 回答

TA貢獻1874條經驗 獲得超12個贊
在過濾器承諾數組的情況下出現相同的錯誤:
const promises = ids.map((id) => <some BE API call>);
const resolvedPromises = await Promise.allSettled(promises);
resolvedPromises.filter(({ status }) => status === 'fulfilled').map((p) => p.value);
問題是allSettledreturns PromiseSettledResult,它根本沒有導出(我在 lib.es2020.promise 中使用tsconfig):
interface PromiseFulfilledResult<T> {
status: "fulfilled";
value: T;
}
interface PromiseRejectedResult {
status: "rejected";
reason: any;
}
type PromiseSettledResult<T> = PromiseFulfilledResult<T> | PromiseRejectedResult;
并且.map不明白所有的rejected承諾都在filtered方法中被過濾了。
所以,我什至無法導入類型并將值轉換為它們。
作為臨時解決方案,我用注釋抑制了 ESLint 和 TSC 規則:
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
然后我PromiseFulfilledResult在項目中創建了相同的接口并使用了類型轉換:
resolvedPromises.filter(({ status }) => status === 'fulfilled').map((p) => (p as PromiseFulfilledResult).value);
結果我擺脫了 on error 和 ESLint/TS rules ignoring comments。

TA貢獻1818條經驗 獲得超8個贊
你只有一個狀態滿足的值屬性,而你沒有檢查它。
所以使用我自己的例子,它可以固定如下:
const p1 = Promise.resolve(50);
const p2 = Promise.resolve(100);
const promiseArray = [p1, p2];
Promise.allSettled( promiseArray ).
then( results => results.forEach( result =>
console.log(result.status,
result.status === 'fulfilled' && result.value
);
));
它現在驗證承諾是否已實現,然后打印值(如果是的話)。

TA貢獻1835條經驗 獲得超7個贊
如果在調用該方法后進行類型聲明,則可以避免此錯誤allSettled。例如,您可以立即為打字稿輸入一個類型,如下所示:
const promises = await Promise.allSettled([
fetch(url).then((response) => response.json()),
fetch(url).then((response) => response.json()),
]) as {status: 'fulfilled' | 'rejected', value: SomeType}[];
之后它將正常工作:
const resolvedPromises = promises.filter(({ status }) => status === 'fulfilled');
const responses = resolvedPromises.map((promise) => promise.value);

TA貢獻1836條經驗 獲得超13個贊
您可以只鍵入 cast 的結果Promise.allSettled,例如:
const [
someData,
otherData
] = (await Promise.allSettled([
this.someRepository.count(),
this.otherRepository.count(),
])) as PromiseFulfilledResult<number>[];
// will verify the promises, but ts doesn't get it
this.verify(someData, otherData)
console.log(otherData.value) // ts is okay
Number 是從 promise 返回的類型,如果你想用不同的類型輸入 promises,你也可以使用[PromiseFulfilledResult<number>, PromiseFulfilledResult<string>]
添加回答
舉報