che*_*alt 4 javascript promise
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)Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
[
{"name":"Alice","delta":2158},
{"name":"Bob","delta":4156},
{"name":"Claire","delta":1255}
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2329 次 |
| 最近记录: |