javascriptpromise

With Promise.race(), what happens to losing promises?


Promise.race(promise1, promise2, ...) returns a promise with the resolve/reject result for the "fastest" promise from the list.

What happens to the other promises, i.e. those that "lose" the race?

Testing 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 that I know of.

Is this correct ?


Solution

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