-2

I need to resolve my promise when the first ajax call is successfull and return true, otherwise i need to wait for all rejected promises before return false.

Can I do it with promise.race, allSettled or similars?

t.niese
  • 39,256
  • 9
  • 74
  • 101
Davide Cavallini
  • 216
  • 4
  • 15
  • try `promise.all()` – Karl L Jul 01 '20 at 07:57
  • Does this answer your question? [Wait until all promises complete even if some rejected](https://stackoverflow.com/questions/31424561/wait-until-all-promises-complete-even-if-some-rejected) – Robin Jul 01 '20 at 07:58
  • @user9879287 `Posmise.all()` waits for all Promises to be resolved or rejects immediately when one of them is rejected. That is the opposite of what the OP is asking for. – t.niese Jul 01 '20 at 07:59

1 Answers1

1

You look for Promise.any:

[...]as soon as one of the promises in the iterable fulfils, returns a single promise that resolves with the value from that promise. If no promises in the iterable fulfil (if all of the given promises are rejected), then the returned promise is rejected with an AggregateError[...]

But it is still experimental, but you could check for existing polyfills (I haven't checked that one for correctness, but on the first look it seems valid):

function any(promises) {
  return Promise.all(
    promises.map(promise =>
      promise.then(val => {
        throw val;
      }, reason => reason),
    ),
  ).then(reasons => {
    throw reasons;
  }, firstResolved => firstResolved);
};
t.niese
  • 39,256
  • 9
  • 74
  • 101