Are JavaScript Promise asynchronous?

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’).

Leave a Comment