为何Promise无法并发执行?代码无输出问题咨询
你的Promise代码无输出的原因解析
先看你这段代码:
const x = Promise.race([ new Promise(resolve => { while(true);}), new Promise(resolve => { let i = 0; while((i++)<100);console.log(2); resolve(); }), new Promise(resolve => { let i = 0; while((i++)<2000);console.log(3); resolve(); }), ]); console.log('This line ran');
核心问题出在Promise的executor函数(传给new Promise的回调)是同步执行的——这是很多人对Promise的常见误解:以为Promise里的代码全是异步的,但其实executor是在创建Promise的瞬间就同步执行的。
具体来说:
- 当你创建第一个
new Promise时,它的executor里是while(true)的死循环,会直接霸占主线程,永远不会结束。 - 主线程被这个死循环卡死,后面的所有代码(包括另外两个Promise的executor、最后的
console.log('This line ran'))都没有机会执行,所以你看不到任何输出。
换成Promise.all也一样,因为问题根源不是race或all的逻辑,而是第一个Promise的executor同步阻塞了整个主线程。
如果要验证Promise的异步特性,你得把阻塞逻辑改成真正的异步操作,比如用setTimeout:
const x = Promise.race([ new Promise(resolve => { setTimeout(() => resolve(), 1000); }), // 异步延迟 new Promise(resolve => { let i = 0; while((i++)<100);console.log(2); resolve(); }), new Promise(resolve => { let i = 0; while((i++)<2000);console.log(3); resolve(); }), ]); console.log('This line ran');
这时你会先看到This line ran,然后是2、3,因为executor里的同步循环会执行,但不会阻塞后续代码(除了自身的循环),而setTimeout的回调会在异步队列里等待。
内容的提问来源于stack exchange,提问作者Ashutosh Mohanta
相关产品推荐
相关产品推荐

