5 回答

TA貢獻1848條經驗 獲得超10個贊
使用類型保護。比內聯類型保護更優雅的解決方案是將它們定義為單獨的函數,并且通過泛型綁定,您也可以獲得已實現的承諾的正確值,并且可以重用以滿足任何過濾需求allSettled
。
不需要鑄造(通常應該避免)。
const isRejected = (input: PromiseSettledResult<unknown>): input is PromiseRejectedResult =>?
? input.status === 'rejected'
const isFulfilled = <T>(input: PromiseSettledResult<T>): input is PromiseFulfilledResult<T> =>?
? input.status === 'fulfilled'
const myPromise = async () => Promise.resolve("hello world");
const data = await Promise.allSettled([myPromise()]);
const response = data.find(isFulfilled)?.value
const error = data.find(isRejected)?.reason

TA貢獻1806條經驗 獲得超8個贊
TypeScript 在檢查類型時不知道類型是否為PromiseFulfilledResult/ PromiseRejectedResult。
唯一的辦法就是鑄造承諾的結果。之所以可以這樣做,是因為您已經驗證了已解決的承諾已實現或已拒絕。
看這個例子:
const myPromise = async (): Promise<string> => {
? return new Promise((resolve) => {
? ? resolve("hello world");
? });
};
const data = await Promise.allSettled([myPromise()]);
const response = (data.find(
? (res) => res.status === "fulfilled"
) as PromiseFulfilledResult<string> | undefined)?.value;
if (!response) {
? const error = (data.find(
? ? (res) => res.status === "rejected"
? ) as PromiseRejectedResult | undefined)?.reason;
? throw new Error(error);
}

TA貢獻1880條經驗 獲得超4個贊
使用類型保護:
const isFulfilled = <T,>(p:PromiseSettledResult<T>): p is PromiseFulfilledResult<T> => p.status === 'fulfilled';
const isRejected = <T,>(p:PromiseSettledResult<T>): p is PromiseRejectedResult => p.status === 'rejected';
const results = await Promise.allSettled(...);
const fulfilledValues = results.filter(isFulfilled).map(p => p.value);
const rejectedReasons = results.filter(isRejected).map(p => p.reason);

TA貢獻1815條經驗 獲得超10個贊
這讓ts不生氣。
const rawResponse = await Promise.allSettled(promiseArray);
const response = rawResponse.filter((res) => res.status === 'fulfilled') as PromiseFulfilledResult<any>[];
const result = response[0].value

TA貢獻1757條經驗 獲得超7個贊
將回調定義find為類型保護,返回類型謂詞:
type IMyPromiseResult = string
const response = data.find(
(res): res is PromiseFulfilledResult<string> => res.status === 'fulfilled'
)?.value;
if (!response) {
const error = data.find(
(res): res is PromiseRejectedResult => res.status === 'rejected'
)?.reason;
throw new Error(error);
}
添加回答
舉報