【问题标题】:typescript get values of Promise.allSettled打字稿获取 Promise.allSettled 的值
【发布时间】:2020-07-18 19:43:07
【问题描述】:

我想在打字稿代码中获取 Promise allSettled 结果的值。这在 JavaScript 中运行良好。

  Promise.allSettled([
      Promise.resolve(33),
      new Promise(resolve => setTimeout(() => resolve(1000), 0)),
      25000,
      Promise.reject(new Error('failed!'))
    ])
    .then(values => {
      let allValues = values.filter(c=>c.status === 'fulfilled').map(v=>v.value);
      console.log(allValues);
    });

但在打字稿中我找不到正确的语法。该项目只有状态并且没有价值属性。我正在使用最新版本的 typescript 3.9.7

【问题讨论】:

  • 您能提供更多信息吗?你在 Typescript 中使用什么语法?您收到任何错误吗?
  • 使用与 JavaScript 相同的语法,我得到编译时错误。我只想在打字稿中做同样的工作。
  • @PoulKruijt 好的。像javascript一样,我可以根据打字稿中的状态过滤结果,但是如何获取结果的值属性?
  • 你能给你的 tsconfig.json 吗?
  • "我得到编译时错误" - 你得到哪个错误,在什么声明上?

标签: javascript angular typescript promise


【解决方案1】:

好的,我终于找到了在 typescript 中使用 Promise.allSettled 的正确语法:

Promise.allSettled([
  Promise.resolve(1000),
  new Promise(resolve => setTimeout(() => resolve(2000), 0)),
  1500,
  Promise.reject(new Error('failed'))
])
.then(values => {
  let allValues = values.filter(c=>c.status === 'fulfilled').map(c=> <PromiseFulfilledResult<any>>c).map(c=>c.value);
  console.log(allValues);
  let failedResults =  values.filter(c=>c.status === 'rejected').map(c=> <PromiseRejectedResult>c).map(c=>c.reason);
  console.log(failedResults);
});

【讨论】:

    猜你喜欢
    • 2018-09-08
    • 1970-01-01
    • 2018-11-14
    • 2022-01-12
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多