javascript - 在 Promise.race() 中,失去承诺会发生什么?
问题描述
Promise.race( list_of_promises ) 返回一个承诺,其中包含列表中“最快”承诺的解决/拒绝结果。
我的问题是其他承诺会发生什么?(那些输掉比赛的人......)
使用 node.js 在控制台模式下进行测试似乎表明它们继续运行。
这似乎与没有办法“杀死”一个承诺的事实一致。(我的意思是我所知道的程序员无法使用)。
这个对吗 ?
解决方案
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}
]
推荐阅读
- spring - Spring Data:使用其他字段获取计数
- java - 搜索两个日期之间所有日期的平均温度
- mysql - 从 docker 容器 mysql 运行 db 脚本
- flutter - 如何在滚动视图中实现滚动视图
- python - 检查熊猫数据框并在同一行的其他列中显示其他元素的最快方法
- delphi - dcc 命令行编译器的 -i 和 -u 参数有什么区别?
- java - 如何在 apache poi 中为 word 创建 commentsExtended.xml、commentsExtensible、commentdIds 文件
- javascript - 使用 map 去除复杂的 if 语句
- python - 找到一个短语/字符串并阅读与该短语/字符串对应的行
- apache-kafka - KStreams - “提交任务偏移量{}”的无数日志