鐵人賽
React
javascript
nodejs
鐵人賽第25天,前幾天我們學會了Promise
及Promise-chain
,對於異步程式有了基本的了解。今天我們要深入探討使用它的眉角,搞懂它,將更清楚它背後的運作方式。
console.log("code finished");
let promise = Promise.resolve();
promise.then(() => console.log("promise done!"));
promise.then(() => console.log("promise done!"));
promise.then(() => console.log("promise done!"));
console.log("code finished"); // <-- !!!
let promise2 = Promise.resolve();
promise2.then(() => console.log("promise2 done!"));
promise2.then(() => console.log("promise2 done!"));
promise2.then(() => console.log("promise2 done!"));
code finished //<-- 怎麼回事!?前面不是有promise在運行了嗎?
promise done!
promise done!
promise done!
promise2 done!
promise2 done!
promise2 done!
Microtask Queue
來處理這些Promise Jobs
。JS Engine
會先解析程式碼,然後依序執行:
- 非Promise的script
- Promise的then/catch/finally異步程式(依時間順序執行)
let promise = Promise.resolve();
promise.then(() => setTimeout(()=>console.log("===>5secs promise done!")), 5000); // 5 secs後執行
promise.then(() => console.log("promise done!")); // 立即執行
promise.then(() => console.log("promise done!")); // 立即執行
console.log("code finished"); // <--先執行
let promise2 = Promise.resolve();
promise2.then(() => setTimeout(()=>console.log("===>1secs promise2 done!")), 1000); // 1 sec後執行
promise2.then(() => console.log("promise2 done!")); // 立即執行
promise2.then(() => console.log("promise2 done!")); // 立即執行
code finished
promise done!
promise done!
promise2 done!
promise2 done!
===>5secs promise done!
===>1secs promise2 done!
d
一定會比c
還要早執行。c
執行完之後,接著執行d
,該如何進行呢?Promise chain
登場囉!,你只要在Promise.then(C)
後面多加一個.then(d)
,就可以囉!let promise = Promise.resolve();
promise.then(() => setTimeout(()=>console.log("===>5secs promise done!")), 5000);
promise
.then(() => console.log("promise done!"))
.then(()=>console.log("code finished")) //<--接續執行
let promise2 = Promise.resolve();
promise2.then(() => setTimeout(()=>console.log("===>1secs promise2 done!")), 1000);
promise done!
code finished
===>5secs promise done!
===>1secs promise2 done!
JS
裡扮演著很重要的角色,讓我們的前端程式能執行得更有效率,好東西~不學嗎~?