in Promise.race(), what happens to loosing promises?

Viewed 969

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 ?

1 Answers

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}
]
Related