3

Promise.race( list_of_promises ) returns a promise with the resolve/reject result for the 'fastest' promise from the list.

My question is what happens to the other promises ? (those who lose the race...)

Testing in console mode with node.js seems to indicate that they continue running.

This seems consistent with the fact that there is no way to 'kill' a promise. (I mean no way available to the programmer that I know of).

is this correct ?

chetzacoalt
  • 145
  • 10
  • 2
    Don't know of too many races where the runners stop when someone wins. Just sayin'. – Jared Farrish May 19 '21 at 13:29
  • 3
    Correct. Because promises don't "run". They are just markers for some async operation. The only thing you can get from a promise is the end result of the operation - you cannot affect the operation. – VLAZ May 19 '21 at 13:29
  • Does this answer your question? [Is it a documented behavior that Promise.all and Promise.race effectively make all promises "handled"?](https://stackoverflow.com/questions/64317888/is-it-a-documented-behavior-that-promise-all-and-promise-race-effectively-make-a) – Manuel Spigolon May 20 '21 at 08:25

1 Answers1

5

All promises in a race will continue running even after the first one crosses the finish line -

const sleep = ms =>
  new Promise(r => setTimeout(r, ms))

async function runner (name) {
  const start = Date.now()
  console.log(`${name} starts the race`)
  await sleep(Math.random() * 5000)
  console.log(`${name} finishes the race`)
  return { name, delta: Date.now() - start }
}

const runners =
  [ runner("Alice"), runner("Bob"), runner("Claire") ]

Promise.race(runners)
  .then(({ name }) => console.log(`!!!${name} wins the race!!!`))
  .catch(console.error)
  
Promise.all(runners)
  .then(JSON.stringify)
  .then(console.log, console.error)
Alice starts the race
Bob starts the race
Claire starts the race
Claire finishes the race
!!!Claire wins the race!!!
Alice finishes the race
Bob finishes the race
[ 
  {"name":"Alice","delta":2158},
  {"name":"Bob","delta":4156},
  {"name":"Claire","delta":1255}
]
Mulan
  • 129,518
  • 31
  • 228
  • 259
  • Is there are way to stop Alice and Bob from running once Claire wins the race? – Abdullah Khilji May 29 '22 at 07:42
  • 1
    @AbdullahKhilji using native Promise, not at this time. See [this Q&A](https://stackoverflow.com/a/30235261/633183) for details. The short answer is you have to use a 3rd-party promise or implement a promise that is capable of this behavior. – Mulan May 29 '22 at 13:39