玩家抱怨《刺客信條:英靈殿》氪金裝備太多
阿新 • • 發佈:2021-02-10
promise巢狀promise誰先執行
new Promise(resolve => {
console.log(1)
resolve(5)
new Promise(resolve => {
resolve(4)
console.log(2)
}).then(num => {
console.log(num)
})
}).then (num => {
console.log(num)
})
console.log(3)
輸出12345,朋友問我為啥不是12354。
我說,非同步任務完成後進入的是事件佇列,第二個promise的then是優先註冊並執行完的,所以輸出12345。然後朋友給我發了個別人的解釋,說是Chrome的bug導致(promise執行後面跟著then的直接執行了,沒必要等到下次),正常應該是12354
所以本著嚴(無)謹(聊)的態度進行試驗:
- Chrome的bug導致,(實驗思路:不使用Chrome,使用Firefox,edge或者ie就會輸出12354)
很顯然這並不是Chrome的bug,或者說著並不單獨是Chrome的bug
2. promise執行後面跟著then的直接執行了,沒必要等到下次,(實驗思路:利用全域性變數把兩個promise儲存起來不再例項化後直接跟then)
var first, second
first = new Promise(res => {
console.log(1)
res(5)
second = new Promise(resolve => {
resolve (4)
console.log(2)
})
})
second.then(num => {
console.log(num)
})
first.then(num => {
console.log(num)
})
console.log(3)
試驗結果12345。
3. 都到這一步了,那就把first與second交換位置吧
var first, second
first = new Promise(res => {
console.log(1)
res(5)
second = new Promise(resolve => {
resolve(4)
console.log(2)
})
})
first.then(num => {
console.log(num)
})
second.then(num => {
console.log(num)
})
試驗結果12354
個人推論:js是單執行緒解釋型語言,在執行第一個promise的時候裡面是同步的,並且一行一行的進行解釋執行,當遇到第二個promise的時候第二個promise裡面執行,第二個promise的then方法註冊執行完成後第一個promise才進行註冊(第二個promise的then方法先於第一個promise的then方法註冊),噹噹前執行棧為空的時候,因為兩個promise裡面的resolve是立即執行的所以微任務佇列裡的第二個promise是早於第一個promise的所以輸出的是12345