Are JavaScript Promise asynchronous?
Solution 1
I think you are working under a misunderstanding. JavaScript code is always* blocking; that is because it runs on a single thread. The advantages of the asynchronous style of coding in Javascript is that external operations like I/O do not require blocking that thread. The callback that processes the response from the I/O is still blocking though and no other JavaScript can run concurrently.
* Unless you consider running multiple processes (or WebWorkers in a browser context).
Now for your specific questions:
Just a quick question of clarifications: is JavaScript Promise asynchronous?
No, the callback passed into the Promise constructor is executed immediately and synchronously, though it is definitely possible to start an asynchronous task, such as a timeout or writing to a file and wait until that asynchronous task has completed before resolving the promise; in fact that is the primary use-case of promises.
Would this approach with setTimeout work to make code non-blocking inside a Promise?
No, all it does is change the order of execution. The rest of your script will execute until completion and then when there is nothing more for it to do the callback for setTimeout will be executed.
For clarification:
console.log( 'a' );
new Promise( function ( ) {
console.log( 'b' );
setTimeout( function ( ) {
console.log( 'D' );
}, 0 );
} );
// Other synchronous stuff, that possibly takes a very long time to process
console.log( 'c' );
The above program deterministically prints:
a
b
c
D
That is because the callback for the setTimeout won't execute until the main thread has nothing left to do (after logging 'c').
Solution 2
const p = new Promise((resolve, reject) => {
if (1 + 1 === 2) {
resolve("A");
} else {
reject("B");
}
});
p.then((name) => console.log(name)).catch((name) => console.log(name));
console.log("hello world");
Promise doesn't block the next lines while it's in pending state. So, it works asynchronously.
Related videos on Youtube
Jane Wayne
Updated on September 14, 2022Comments
-
Jane Wayne over 1 year
Just a quick question of clarifications: is JavaScript
Promise
asynchronous? I've been reading a lot of posts onPromise
and async programming (namely ajax requests). IfPromise
is not async, how do we make it so?For example, I have a function to wrap a function
f
with argument arrayargs
inside aPromise
. Nothing aboutf
inherently is async.function getPromise(f, args) { return new Promise(function(resolve, reject) { var result = f.apply(undefined, args); resolve(result); }); }
To make this async, I read some SO posts and decided that the
setTimeout
is what a lot of people were recommending to make code non-blocking.function getPromise(f, args) { return new Promise(function(resolve, reject) { setTimeout(function() { var r = f.apply(undefined, args); resolve(r); }, 0); }); }
Would this approach with
setTimeout
work to make code non-blocking inside aPromise
?(Note that I am not relying on any third-party Promise API, just what is supported by the browsers).
-
Robby Cornelissen about 8 years
-
Bergi over 7 yearspossible duplicate of Is JavaScript Promise Callback executed Asynchronously
-
-
Jane Wayne about 8 yearsI understand a little better now. I suppose (unless I bend over backwards and get to know WebWorkers), using
Promise
won't make my code non-blocking or aysnc. Basically, I will just continue to usePromise
because at least now I don't have nested callback handling. Thanks. -
Chris Paton about 5 yearsI know this answer was written a while ago, but I'm curious if anyone has any references for this? According to MDN, Promises are asynchronous: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/….
-
Sachin Ramdhan Boob almost 4 yearsI too am trying to figure out, whether a Promise is asynchronous or synchronous. Looking at - developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/… 'Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.' I understand that promise itself is synchronous, however, it is most generally used in conjunction with asyn functions. Hence, it is said - 'A Promise is an object representing the eventual completion or failure of an asynchronous operation' Examples there include both async and normal functions.
-
variable about 2 yearsIf Promise is not async, then how come it is allows to use the await keyword - example:
await new Promise...
?