Async function without await in Javascript

后端 未结 4 905
南旧
南旧 2020-11-29 03:36

I have two functions a and b that are asynchronous, the former without await and the later with await. They both log some

4条回答
  •  遥遥无期
    2020-11-29 04:26

    Everything is synchronous until a Javascript asynchronous function is executed. In using async-await await is asynchronous and everything after await is placed in event queue. Similar to .then().

    To better explain take this example:

    function main() {
      return new Promise( resolve => {
        console.log(3);
        resolve(4);
        console.log(5);
      });
    }
    
    async function f(){
        console.log(2);
        let r = await main();
        console.log(r);
    }
    
    console.log(1);
    f();
    console.log(6);
    

    As await is asynchronous and rest all is synchronous including promise thus output is

    1
    2
    3
    5
    6
    // Async happened, await for main()
    4
    

    Similar behavior of main() is without promise too:

    function main() {
        console.log(3);
        return 4;
    }
    
    async function f(){
        console.log(2);
        let r = await main();
        console.log(r);
    }
    
    console.log(1);
    f();
    console.log(5);
    

    Output:

    1
    2
    3
    5
    // Asynchronous happened, await for main()
    4
    

    Just removing await will make whole async function synchronous which it is.

    function main() {
        console.log(3);
        return 4;
    }
    
    async function f(){
        console.log(2);
        let r = main();
        console.log(r);
    }
    
    console.log(1);
    f();
    console.log(5);
    

    Output:

    1
    2
    3
    4
    5
    

提交回复
热议问题