javascript - 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.json
为ES2020
能够使用该方法本身。
解决方案
在过滤器承诺数组的情况下得到同样的错误:
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
):PromiseSettledResult
tsconfig
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 规则。
推荐阅读
- angular - 更改项目数组时 cdk-virtual-scroll-viewport 出错
- python - 如何删除行和列的索引名称?(轴=0 & 轴=1)
- r - 任何时候只为 10 号之前的日期生成 NA 日期
- php - 捕获字符串中的第一个单词和数字
- javascript - 在 Python 中将图像上传到服务器时,是否有图像大小限制?
- r - 如何创建不包括缺失日期值的新变量?
- c# - 将 log4net 的程序集信息配置添加到 .NET Core xunit 项目中
- android - 减去日期只返回分钟差异
- python - 去掉图中的次要框
- ansible - 使用 Ansible 将多个用户添加到 linux 系统