有没有办法获得仅已解决的承诺的价值?

发布于 2025-01-17 04:20:14 字数 439 浏览 3 评论 0原文

我正在调用多个服务,其中包括 JavaScript 应用程序中的网络调用和其他异步服务。

起初我一一援引这些承诺。从长远来看,由于我调用更多的服务,它变得很难维护。

我在互联网上的某个地方读到我们可以使用 Promise.all() 将所有承诺分组并一次执行所有内容。

问题是,如果任何一个承诺被拒绝,所有其他承诺也被拒绝,这不是我需要的。

我正在状态仪表板中工作,需要对多个服务执行 ping 操作并显示服务是否启动。通过使用 Promise.all,它并没有按照我希望的方式工作。

尝试了另一种方法 Promise.any(),但它只是在任何一个解决时才解决。

看了一下MDN文档,有很多promise的函数,这对我来说是压倒性的,因为我是JavaScript的初学者。

目前,我创建了一个自己的服务,负责调用所有承诺并计算响应。有没有更干净的方法来做到这一点?

I'm calling multiple services which includes network calls and other asynchronous services in my JavaScript application.

At first I was invoking these promises one by one. In the long run it's getting hard to maintain since I'm invoking more services.

I read somewhere in the internet that we can use Promise.all() to group all promises and execute everything at a time.

The issue is, if any one of the promise is getting rejected all other promises are also getting rejected, this is not what I need.

I'm working in a status dashboard where I need to ping multiple services and show whether the service is up or not. By using Promise.all, it's not working in a way I wished.

Tried another method Promise.any(), but it just resolves when any one is resolved.

Took a look at MDN docs, there are many functions for promise it's overwhelming to me because I'm a beginner in JavaScript.

Currently I've created a very own service which takes care of calling all the promises and counts with the response. Is there any cleaner way to do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

反目相谮 2025-01-24 04:20:14

使用 Promise.allSettled,然后过滤掉那些未实现的。

Promise.allSettled([
  Promise.resolve(3),
  Promise.reject(4),
  Promise.resolve(5),
])
  .then((results) => {
    const allFulfilledValues = results
      .filter(r => r.status === 'fulfilled')
      .map(r => r.value);
    console.log(allFulfilledValues);
  });

Use Promise.allSettled, then filter out those that weren't fulfilled.

Promise.allSettled([
  Promise.resolve(3),
  Promise.reject(4),
  Promise.resolve(5),
])
  .then((results) => {
    const allFulfilledValues = results
      .filter(r => r.status === 'fulfilled')
      .map(r => r.value);
    console.log(allFulfilledValues);
  });

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文