How does promise make code asynchronous?

后端 未结 2 926
-上瘾入骨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.

提交回复
热议问题