How does promise make code asynchronous?

后端 未结 2 962
-上瘾入骨i
-上瘾入骨i 2021-01-21 10:46

I know we all use promises to avoid function callback hell, but my question is where in the event loop the promise code runs and whether the code is really asynchronous.

2条回答
  •  孤独总比滥情好
    2021-01-21 11:30

    In javascript we can not create a synchronous function. There are set predefined asynchronous function and we can use them to make our code asynchronous. These asynchronous function generally takes a callback function as argument to perform tasks on completion of asynchronous task.

    Promises are synchronous, .then() is a asynchronous function. In async-await await is asynchronous and anything written after await is executed after asynchronous await.

    function main(){
      console.log(2);
      return new Promise( (re,rj) => {
        console.log(3);
        re(4);
        console.log(5);
        rj(6);
        console.log(7);
      });
    
    }
    
    console.log(1);
    
    main()
    .then( r=> {
      console.log(r)
    })
    .catch(e=>{
      console.log(e)
    });
    
    console.log(8);
    

    As expected output is

    1
    2
    3
    5
    7
    8
    // asynchronous .then function
    4
    

    Similar thing happen when we use setTimeout, setInterval, API call, fs functions, all asynchronous thing happen at browser/kernel then all callback happens at our Javascript single thread.

提交回复
热议问题