首页 > 解决方案 > 在 Promise.race() 中,失去承诺会发生什么?

问题描述

Promise.race( list_of_promises ) 返回一个承诺,其中包含列表中“最快”承诺的解决/拒绝结果。

我的问题是其他承诺会发生什么?(那些输掉比赛的人......)

使用 node.js 在控制台模式下进行测试似乎表明它们继续运行。

这似乎与没有办法“杀死”一个承诺的事实一致。(我的意思是我所知道的程序员无法使用)。

这个对吗 ?

标签: javascriptpromise

解决方案


race即使在第一个越过终点线之后,a 中的所有承诺仍将继续运行 -

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

推荐阅读