How do you implement a “raceToSuccess” helper, given a list of promises?

后端 未结 7 1826
孤城傲影
孤城傲影 2020-12-02 23:37

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 wo

7条回答
  •  广开言路
    2020-12-02 23:57

    Is there something in the API that permits a "raceToSuccess" kind of behavior

    Soon, there almost certainly will be. There is a Stage 3 proposal for Promise.any:

    Promise.any() takes an iterable of Promise objects and, as soon as one of the promises in the iterable fulfills, returns a single promise that resolves with the value from that promise.

    So, the following syntax will be valid:

    // assume getApi returns a Promise
    
    const promises = [
      getApi('url1'),
      getApi('url2'),
      getApi('url3'),
      getApi('url4'),
    ];
    Promise.any(promises)
      .then((result) => {
        // result will contain the resolve value of the first Promise to resolve
      })
      .catch((err) => {
        // Every Promise rejected
      });
    

    Promise.any has been implemented in Spidermonkey, and there are some polyfills available.

提交回复
热议问题