0

I'll be quick. MDN provides the following example for Promise.race

But that example on their website is a bit misleading, as there is no code that depends on the result of the race. I've adapted the code a bit and it behaves quite weirdly.

const promise1 = new Promise((resolve, reject) => {
  setTimeout(resolve, 500, 'one');
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'two');
});

(async () => {
  let val = 'zero';
  Promise.race([promise1, promise2]).then((result) => {
    val = result;
    console.log("Assigned value", val);
  })
  console.log(val);
})();

If you run the snippet above, you'll see that the result is zero.
I would expect calling then on the race would make the execution synchronous, but apparently, that is not the case.
So how do I do that? What do I need to modify in this example for the last log to print "two"?

Andi Abrudan
  • 104
  • 4
  • 1
    `await` the call of the Promise so that the surrounding function stops while waiting for the Promise to finish. Not really anything to do with `Promise.race` in particular - this would be reproducible with a simple `Promise.resolve()` too – CertainPerformance Nov 27 '22 at 23:16
  • "*there is no code that depends on the result of the race.*" - sure there is, all of the examples at MDN have something like `.then((value) => { console.log(value); // Both resolve, but promise2 is faster });` – Bergi Nov 28 '22 at 02:44

0 Answers0