async/wait 多個async函數嵌套


1. 假如函數

async function A(){
  await customFun();  
  console.log("A");  
}

A()會等到customFun()的函數體內所有的代碼執行結束,再執行console.log("A")。  

async function customFun() {
    console.log("customFun")
    await new Promise((res,rej)=>{
        let t = 1000;
        setTimeout(()=>{
            console.log(`setTimeout ${t}ms`);
            res(777);
    
        }
        , t);
        console.log(`promise ${t}`);
    }
    ).then((result)=>{
        console.log(`result ${result}`)
    }
    );
    console.log("f-2")
}

如果customFun()的函數體內使用了await,也會執行customFun()的函數await行下面所有代碼,然后再返回執行。

 結果為:
customFun
promise 1000
setTimeout 1000ms
result 777
f-2

 

1.實例

async function f() {
    await console.log("f");
    console.log("f-2")
}

async function f0() {
    console.log("f0");
    await f();
    console.log("f0-2");
}

async function f1() {
    console.log("f1")
    await f0();
    //加了await, 會等到f0()的”f0-2"輸出之后再輸出f1-2;沒加await,
    console.log("f1-2")

}

async function f2() {
    console.log("f2")
    await f1();
    console.log("f2-2")
}

// f2();
// f2
// f1
// f0
// f
// f-2
// f0-2
// f1-2
// f2-2

 

2. 

console.log("start")
async function f() {
    console.log("f")
    await new Promise((res,rej)=>{
        let t = 1000;
        setTimeout(()=>{
            console.log(`setTimeout ${t}ms`);
            res(777);
    
        }
        , t);
        console.log(`promise ${t}`);
    }
    ).then((result)=>{
        console.log(`result ${result}`)
    }
    );
    console.log("f-2")
}

async function f0() {
    console.log("f0");
    await f();  //在這兒取消await 或者加上await,分析結果。
    console.log("f0-2");
}

async function f1() {
    console.log("f1")
    await f0();
    //加了await, 會等到f0()的”f0-2"輸出之后再輸出f1-2;沒加await,
    console.log("f1-2")
}
async function f2() {
    console.log("f2")
    await f1();
    console.log("f2-2")
}

f2();
console.log("end")

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM