Promise is synchronous or asynchronous in node js

udayakumar picture udayakumar · Apr 19, 2018 · Viewed 8.6k times · Source

I have lot of confusion in promise. It's a synchronous or asynchronous ?

return new Promise (function(resolved,reject){
    //sync or async? 
});

Answer

CertainPerformance picture CertainPerformance · Apr 19, 2018

The function you pass into the Promise constructor runs synchronously, but anything that depends on its resolution will be called asynchronously. Even if the promise resolves immediately, any handlers will execute asynchronously (similar to when you setTimeout(fn, 0)) - the main thread runs to the end first.

This is true no matter your Javascript environment - no matter whether you're in Node or a browser.

console.log('start');
const myProm = new Promise(function(resolve, reject) {
  console.log('running');
  resolve();
});
myProm.then(() => console.log('resolved'));
console.log('end of main block');