提出問題,問題代碼為
setTimeout(function(){console.log(1)},0); new Promise(function(resolve){ console.log(2) for( var i=0 ; i<100 ; i++ ){ i==99 && resolve() } console.log(3) }).then(function(){ console.log(4) }); console.log(5);
在控制台運行其結果為:
疑問:既然promise.then和setTimeout都是異步的,那么在事件循環隊列中 promise.then的事件應該排在setTimeout后面,那為什么promise.then卻在setTimeout前面被打印了出來?
個人理解:瀏覽器讀取script標簽中的代碼也是一個事件隊列,Promise的任務會在當前事件循環末尾中執行,而setTimeout中的任務是在下一次事件循環執行。