如何在打字稿中使用promise.allSettled?

Typescript 构建失败,因为它似乎不喜欢,Promise.allSetttled即使我已经设置了 ts config coilerOptions"lib": [ "ES2020.Promise" ],


似乎 的响应promise.allSettled不包括resultor reason。


运行 typescript build 时出现以下错误:


Property 'reason' does not exist on type 'PromiseSettledResult<IMyPromiseResult>'.


Property 'value' does not exist on type 'PromiseRejectedResult'.

我的代码块如下所示,正如您所看到的,我正在尝试访问reason每个result已解决的承诺。


const myPromise = async () : Promise<IMyPromiseResult> {

  return new Promise((resolve) => {

    resolve("hello world")

  })

}


const data = await Promise.allSettled([

  myPromise()

]);


const response = data.find(res => res.status === 'fulfilled')?.result;


if(!response) {

  const error = data.find(res => res.status === 'rejected')?.reason;

  throw new Error(error);

}

如何更新 Promise.allSettled 声明以包含正确的接口?


一只名叫tom的猫
浏览 179回答 5
5回答

慕桂英546537

使用类型保护。比内联类型保护更优雅的解决方案是将它们定义为单独的函数,并且通过泛型绑定,您也可以获得已实现的承诺的正确值,并且可以重用以满足任何过滤需求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)?.valueconst error = data.find(isRejected)?.reason

慕森卡

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);}

慕村225694

使用类型保护: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);

动漫人物

这让ts不生气。const rawResponse = await Promise.allSettled(promiseArray);const response = rawResponse.filter((res) => res.status === 'fulfilled') as PromiseFulfilledResult<any>[];const result = response[0].value

长风秋雁

将回调定义find为类型保护,返回类型谓词:type IMyPromiseResult = stringconst response = data.find(&nbsp; (res): res is PromiseFulfilledResult<string> => res.status === 'fulfilled')?.value;if (!response) {&nbsp; const error = data.find(&nbsp; &nbsp; (res): res is PromiseRejectedResult => res.status === 'rejected'&nbsp; )?.reason;&nbsp; throw new Error(error);}演示游乐场
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript