5 回答

TA貢獻1848條經(jīng)驗 獲得超10個贊
使用類型保護。比內(nèi)聯(lián)類型保護更優(yōu)雅的解決方案是將它們定義為單獨的函數(shù),并且通過泛型綁定,您也可以獲得已實現(xiàn)的承諾的正確值,并且可以重用以滿足任何過濾需求allSettled
。
不需要鑄造(通常應(yīng)該避免)。
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條經(jīng)驗 獲得超8個贊
TypeScript 在檢查類型時不知道類型是否為PromiseFulfilledResult/ PromiseRejectedResult。
唯一的辦法就是鑄造承諾的結(jié)果。之所以可以這樣做,是因為您已經(jīng)驗證了已解決的承諾已實現(xiàn)或已拒絕。
看這個例子:
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條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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條經(jīng)驗 獲得超7個贊
將回調(diào)定義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);
}
添加回答
舉報