How does promise make code asynchronous?

后端 未结 2 925
-上瘾入骨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:29

    How does promise make code asynchronous?

    It doesn't.

    A promise provides a standard interface (e.g. with a .then() method) for handling asynchronous functions.

    If everything done inside a promise is non-asynchronous, then the code is still non-asynchronous.

    const p = new Promise((resolve, reject) => {
      console.log(1);
      resolve();
      console.log(2);
    
    });
    console.log(3);

    You can see, above, that the Promise is blocking just as any other non-asynchronous code is.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题