首页 > 解决方案 > Promise.allSettled() 响应的类型错误

问题描述

我最近一直在尝试在带有 Typescript 的 NodeJS 上使用 Promise.allSettled,但我遇到了响应问题。allSettled 方法返回一个数组status: "rejected" | "fulfilled"和一个值,以防它被满足。问题是,当我尝试访问响应的值时,出现以下错误:

Property 'value' does not exist on type 'PromiseSettledResult<unknown>'.
Property 'value' does not exist on type 'PromiseRejectedResult'.ts(2339)

下面我将留下一个简单的示例,以便您可以复制代码并自己尝试:

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.value)));

如果我在我的项目上运行此代码,我会得到一个错误,因为result.value最后。

我在 Windows 上的 12.18.3 版本上运行我的节点,并且我已经将我的目标设置tsconfig.jsonES2020能够使用该方法本身。

标签: javascriptnode.jstypescript

解决方案


在过滤器承诺数组的情况下得到同样的错误:

const promises = ids.map((id) => <some BE API call>);
const resolvedPromises = await Promise.allSettled(promises);
resolvedPromises.filter(({ status }) => status === 'fulfilled').map((p) => p.value);

错误截图

问题是return ,它根本没有导出(我使用 lib.es2020.promise in allSettled):PromiseSettledResulttsconfig

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

结果,我摆脱了忽略注释的错误和 ESLint/TS 规则。


推荐阅读