記Promise一個容易被忽略的特性

YDSS發表於2018-06-22

在看webpack bootstrap程式碼的時候,發現new Promise傳的函式是會立即執行

function test() {
    let arr = [1, 2, 3, 4];
    let tasks = arr.map(item => {
        console.log(`task ${item}`)
        let p = new Promise(async function(resolve) {
            console.log(`pre ${item}`)
            await delay(item);  // line 2
            console.log(`outside ${item}`); // line 3
            resolve(item);
        });
        console.log(`after promise ${item}`)
        return p
    });

    Promise.all(tasks).then(() => console.log("done")); // line 4
}
複製程式碼

列印結果:

  1. 立即出現的部分:

    task 1
    pre 1
    after promise 1
    task 2
    pre 2
    after promise 2
    task 3
    pre 3
    after promise 3
    task 4
    pre 4
    after promise 4
    複製程式碼
  2. 延後5秒出現的部分:

    outside 1
    outside 2
    outside 3
    outside 4
    複製程式碼

發現是自己2了,此文灌水了~

相關文章