簡體   English   中英

在 Promise.race() 中,失去承諾會發生什么?

[英]in Promise.race(), what happens to loosing promises?

Promise.race(list_of_promises) 返回一個 promise 以及列表中“最快”promise 的解析/拒絕結果。

我的問題是其他承諾會發生什么? (那些輸掉比賽的人......)

在控制台模式下使用 node.js 進行測試似乎表明它們繼續運行。

這似乎與無法“殺死” promise 的事實一致。 (我的意思是我所知道的程序員無法使用)。

這個對嗎?

即使在第一個越過終點線之后, 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}
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM