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);
}
添加回答
举报