Just a quick question of clarifications: is JavaScript Promise
asynchronous? I've been reading a lot of posts on Promise
and async programming (namely ajax requests). If Promise
is not async, how do we make it so?
For example, I have a function to wrap a function f
with argument array args
inside a Promise
. Nothing about f
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 a Promise
?
(Note that I am not relying on any third-party Promise API, just what is supported by the browsers).
In JavaScript, promises are special objects that help you perform asynchronous operations. You can create a promise using the Promise constructor. You need to pass an executor function to it. In the executor function, you define what you want to do when a promise returns successfully or when it throws an error.
25.5.4 Promises are always asynchronous It states so via the following requirement (2.2. 4) for the then() method: onFulfilled or onRejected must not be called until the execution context stack contains only platform code.
Promises are the foundation of asynchronous programming in modern JavaScript. A promise is an object returned by an asynchronous function, which represents the current state of the operation.
The executor function of a promise also runs in a synchronous manner. Since we have a setTimeout call in the executor function which contains resolve call, it will execute when all asynchronous code is executed.
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').
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With