您如何实现"raceToSuccess"?帮手,给定的诺言清单? [英] How do you implement a "raceToSuccess" helper, given a list of promises?

查看:49
本文介绍了您如何实现"raceToSuccess"?帮手,给定的诺言清单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对ES6 Promise API中的某些内容感到困惑.我可以看到一个明确的用例,可以同时提交多个异步作业,并在首次成功时解决".举例来说,这可以解决以下情况:多个等效服务器可用,但有些服务器可能宕机,而另一些服务器负载重且运行缓慢,因此,我的目标是从第一个服务器获得成功的响应,而忽略其余服务器(是的,我知道这是客户端从服务器的角度进行行为的一种令人讨厌的方式,但这对最终用户而言非常有用;)

I'm puzzled by something in the ES6 Promise API. I can see a clear use case for submitting multiple async jobs concurrently, and "resolving" on the first success. This would, for example, serve a situation where multiple equivalent servers are available, but some are perhaps down, and others heavily loaded and slow, so my goal would be to get a response from the first one to succeed, and ignore the rest (yes, I know this is an obnoxious way for a client to behave from a server's perspective, but it's great for the end user ;)

但是,据我所知,我有全部"或种族"行为. 全部"行为似乎要等到所有请求都完成之后,这意味着即使服务器已经完成,我也必须等待最慢的时间(实际上,我可能不得不等待超时,这将是一场灾难.但是,竞赛"行为似乎使我率先完成,如果这恰巧是失败的话,那也是一场灾难.

However, as far as I can see, I have either "all" or "race" behaviors to play with. The "all" behavior seems to wait until all the requests have completed, which means that I have to wait for the slowest, even if a server has already completed (indeed, I might have to wait for a timeout, with would be a disaster for this scenario.) The "race" behavior, however, seems to give me the first to complete, which if that happens to be a failure, is also a disaster.

API中是否有某种允许"raceToSuccess"行为的行为,或者我必须手动构建它.为此,我将如何手动构建它?

Is there something in the API that permits a "raceToSuccess" kind of behavior, or do I have to build it by hand. For that matter, how would I build it by hand?

作为旁注,我在Java 8 CompletableFuture中发现了同样的难题,它似乎是一个紧密并行的API.那么,我在哲学层面上缺少什么吗?

As a side note, I found the same puzzle in the Java 8 CompletableFuture, which seems to be a closely parallel API. So, am I missing something at a philosophical level?

推荐答案

这是一个经典示例,通过反转逻辑可以使它更加清晰.在这种情况下,您的竞争"是您希望拒绝行为实际上是成功行为.

This is a classic example where inverting your logic makes it much clearer. Your "race" in this case is that you want your rejection behavior to in fact be success behavior.

function oneSuccess(promises){
  return Promise.all(promises.map(p => {
    // If a request fails, count that as a resolution so it will keep
    // waiting for other possible successes. If a request succeeds,
    // treat it as a rejection so Promise.all immediately bails out.
    return p.then(
      val => Promise.reject(val),
      err => Promise.resolve(err)
    );
  })).then(
    // If '.all' resolved, we've just got an array of errors.
    errors => Promise.reject(errors),
    // If '.all' rejected, we've got the result we wanted.
    val => Promise.resolve(val)
  );
}

这篇关于您如何实现"raceToSuccess"?帮手,给定的诺言清单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆