Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(1)
所有
Promise.race()
它是否向呼叫者报告您通过的哪个承诺首先解决/拒绝。它不会影响他们是否解决/拒绝,也不会阻止其他承诺在第一个解决方案后解决。其他承诺中的运营仍在继续,无论使用promise.race()
,它们都会有任何结果。查看您可以在片段中运行的示例:
这会产生此输出:
您可以清楚地看到所有三个承诺都可以根据他们的预期时间表进行。
Promise.race()
本身在您通过的三个承诺中的第一个解决方案中解决,但这不会影响其他两个操作。他们一直在做自己在做的事情。您可以将其视为800m的跑步比赛。
Promise.race()
报告了比赛的获胜者(这是其工作),但仅仅是因为有赢家,其他参与者不会停止跑步。如果他们自己跑步,他们仍然在任何时候都完成比赛。如果您希望其他操作在第一次解决时以某种方式停止,则必须手动编码内容,以便取消其他两个操作,并且它们必须表示可以取消的操作,因为没有自动,内置机制用于停止已经正在进行的异步操作。在上面的示例中,剩余的计时器上必须调用
clear> cleartimeout()
(您必须在某个地方保存timerid值,以便您可以调用clear> clear> cleartimeout()
on他们)。All
Promise.race()
does it report to the caller which of the promises you passed it resolved/rejected first. It does not affect whether they resolve/reject and does not stop the other promises from resolving after the first one has resolved. The operations in those other promises still keep going and they have whatever outcome they would have, regardless of usingPromise.race()
.Look at this example which you can run right in the snippet:
That generates this output:
There you can clearly see that all three promises resolve on their expected schedule.
Promise.race()
itself resolves when the first of the three promises you passed it resolve, but that does not affect the other two operations. They keep doing what they were doing.You can think of it like an 800m running race.
Promise.race()
reports the winner of the race (that is its job), but just because there's a winner, the other participants don't stop running. They still finish the race too in whatever time they would have if they ran on their own.If you want the other operations to somehow stop when the first resolves, you'd have to manually code things so that you cancelled the other two operations and they would have to represent operations that are cancellable as there is no automatic, built-in mechanism for stopping asynchronous operations that are already underway. In my example above, one would have to call
clearTimeout()
on the remaining timers (and you would have to save the timerID values somewhere so you could callclearTimeout()
on them).