Reputation: 3274
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 i a diffrent thread ? or am i synchronized? ')
})
Upvotes: 2
Views: 469
Reputation: 3317
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.
Upvotes: 2
Reputation: 944568
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.
Upvotes: 5