Promise is synchronous or asynchronous in node js
Promises aren't exactly synchronous or asynchronous in and of themselves. When you create a promise the callback you pass to it is immediately executed and no other code can run until that function yields. Consider the following example:
new Promise(function(resolve, reject) {
console.log('foo');
})
console.log('bar');
The code outside the promise has to wait for the code inside the promise (which is synchronous) to complete before it can begin execution.
That said, promises are a common way of dealing with asynchronous code. The most common use case for a promise is to represent some value that's being generated or fetched in an asynchronous fashion. Logic that depends on that value can asynchronously wait until the value is available by registering a callback with .then()
or related Promise methods.
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');
This code makes it clearer:
console.log("0");
new Promise((resolve, reject) => {
console.log("1");
resolve();
}).then(() => {
console.log("2");
});
console.log("3");
The code prints: 0 1 3 2
So, then
runs asynchronously while the main call back function runs synchronously.