简体   繁体   中英

How does promise make code asynchronous?

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.

I mean, is this code asynchronous just because it's run within a promise? Or is the promise not a part of the event loop?

 const p = new Promise((resolve,reject) =>{ resolve('am i part of the event loop ? , am ia diffrent thread ? or am i synchronized? ') }) 

How does promise make code asynchronous?

It doesn't.

A promise provides a standard interface (eg 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM