在 Promise.race() 中,失去承诺会怎样?
in Promise.race(), what happens to loosing promises?
Promise.race( list_of_promises ) returns 列表中 'fastest' 承诺的 resolve/reject 结果的承诺。
我的问题是其他承诺会怎样? (输掉比赛的人...)
使用 node.js 在控制台模式下进行测试似乎表明它们会继续 运行。
这似乎与无法 'kill' 承诺的事实相符。 (我的意思是我认识的程序员没有办法)。
这是正确的吗?
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}
]
Promise.race( list_of_promises ) returns 列表中 'fastest' 承诺的 resolve/reject 结果的承诺。
我的问题是其他承诺会怎样? (输掉比赛的人...)
使用 node.js 在控制台模式下进行测试似乎表明它们会继续 运行。
这似乎与无法 'kill' 承诺的事实相符。 (我的意思是我认识的程序员没有办法)。
这是正确的吗?
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}
]