async與await以及巨集微任務

故心v發表於2020-11-11

async與await以及巨集微任務

一個正在努力愛好運動的程式猿
座右銘:越努力越幸運,越運動越健康,熱愛程式設計,熱愛運動。



一、async與await

async function f(){  //async函式返回的是一個promise物件
        return 'f'
    }
    //f();  //Promise {<resolved>: "f"}
    f().then(function(res){   //預設為成功的狀態,將該函式的返回值傳給then的引數
        console.log(res)
    })

    async function f(){  //async函式返回的是一個promise物件
        return '1234'
    }
    f().then(res=>{
        console.log(res)
    });
    console.log(1);
    // 1     1234


    // await
    // await操作符用於等待一個Promise物件,它只能在非同步函式async function內部使用。
    // 返回值:
    // 返回promise物件的處理結果,如果待等的不是promise物件,則返回該值本身
    // 如果一個promise被傳遞給一個await操作符,await將等待promise正常處理完成並返回其處理結果
    function f2(){
        console.log(4)
    }
    async function f(){
        await f2();     
        console.log(2)   
    }
    f();
    console.log(3); 

    //正常情況下,await命令後面是一個promise物件,它也可以是其它值,如字串,布林值,數值以及普通函式。
    console.log(2)
    async function fn(){
        console.log(3)
        await 100;  
        console.log(1)
    }
    fn()
    console.log(4)

    //await命令後面是一個promise物件
    function p(){
        return new Promise(resolve=>{
            resolve();
            console.log(1)
        });
    };
    async function fn(){
        console.log(2)
        await p();  
        console.log(3)
    }
    fn()

二、巨集微任務

    //巨集任務  setTimeout   setInterval 
    //微任務  promise中的then  async await

    //promise是同步還是非同步?
    console.log(1);  //同步
    let a = new Promise((res,rej)=>{
        console.log(2)  //同步
    });
    console.log(3); //同步
    let a2 = new Promise((res,rej)=>{
        console.log(4)  //同步
    });
    console.log(5);   //同步
 

    console.log(1)   //同步
    let a = new Promise((res,rej) => {  
        res();
        console.log(2); //同步
    });
    a.then(() => {    //非同步
        console.log(3)
    })
    console.log(4);  //同步
    let b = new Promise((res,rej) => {  
        res();
        console.log(5);  //同步
    });
    b.then(() => {  
        console.log(6) //非同步
    })
    console.log(7);   //同步


    setTimeout(()=>{  //巨集任務
        console.log(1)
    },0)
   new Promise((res,rej) => {  
        res();
        console.log(2);  //同步
    }).then(() => {  
        console.log(3) //微任務
    })
    console.log(4)  //同步


    async function f(){  //async函式返回的是一個promise物件
        console.log(5)  //同步
        return '1234'
    }
    f().then(res=>{   //微任務
        console.log(res)
    });
    console.log(1);   //同步

相關文章