[JavaScript] Promise 物件裡的函式執行順序

[JavaScript] Promise 物件裡的函式執行順序

最近重新在看 JavaScript Promise 這個一直沒有搞很懂的概念…

假設以下面的程式來說,它會依序印出什麼呢?

console.log("Before create promise");

const p = new Promise((resolve, reject) => {
    console.log("Before calling setTimeout");
    setTimeout(() => {
        console.log("After 3s timeout");
    }, 3000);
    console.log("After calling setTimeout");
});

console.log("After create promise");

 

本以為直覺是印出 Before create promise 後,就會跑到 After create promise,

結果卻不是這樣,下面是執行的結果:

Before create promise
Before calling setTimeout
After calling setTimeout
After create promise
After 3s timeout

 

也就是說,提供給 Promise 物件的函式參數,

事實上在宣告 Promise 物件時,就立刻執行了,

因此會在印出 Before create promise 後,就印出 Before calling setTimeout。

而 setTimeout() 實際執行的東西要等三秒後才會回來,

因此直接往下印出 After calling timeout。

 

其實這種執行順序,應該是去查看像 JavaScript 引擎的實作最清楚,

不過功力太過淺薄,還是只能用這種方法旁敲側擊囉~

 

參考資料:node.js – Where is the implementation of Promise in nodejs? – Stack Overflow

(本頁面已被瀏覽過 355 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料