【问题标题】:in Promise.race(), what happens to loosing promises?在 Promise.race() 中,失去承诺会发生什么?
【发布时间】:2021-08-08 18:05:09
【问题描述】:

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

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

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

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

这对吗?

【问题讨论】:

标签: javascript promise


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2017-08-11
    • 2017-08-26
    • 2022-01-22
    • 2017-09-07
    • 2016-08-12
    • 2017-12-22
    相关资源
    最近更新 更多