I'm learning Javascript async programming and Promise. I have the following code.
let promiseTest = () => new Promise((resolve, reject) => {
console.log("Inside Promise");
resolve('Promise is resolved');
});
console.log("Before Promise");
promiseTest().then((data) => { console.log(data); });
console.log("After Promise");
I have the function "promiseTest". I want to execute that asynchronously. In real world scenario, it could be a function that fetch the web service or query the database. I was expecting to have the following result from the code.
Before Promise
After Promise
Inside Promise
Promise is resolved
I was expecting that "console.log(" Inside Promise") " will be executed asynchronously since it is inside the Promise function. But the actual result is
Before Promise
Inside Promise
After Promise
Promise is resolved
As you see tin the actual result, Inside Promise is executed synchronously and blocking the main thread. Only the code inside "resolve" is asynchronous. Maybe, my current understanding of javascript Promise is incorrect. How do I modify my existing code to make sure the whole function " promiseTest " is executed asynchronously without blocking the main thread.
The executor function is executed synchronously. Promise doesn't make any code asynchronous; its just a mechanism to get notified when something, that is already asynchronous, has completed.
If you want to make a API call, that is already asynchronous and if you use the fetch API, then you don't need the promise constructor because fetch(...)
already returns a promise.
Only the code inside "resolve" is asynchronous
In your code, resolve()
function is also called synchronously; only the callback function of promiseTest().then(..)
is invoked asynchronously.
How do I modify my existing code to make sure the whole function "promiseTest" is executed asynchronously without blocking the main thread.
You will have to use another thread. Even if you delay the execution of the promiseTest
function using setTimeout
, once it is pushed in the call stack, it will execute synchronously. Nothing else will execute when the delayed promiseTest
function is being executed.
If delaying the execution is what you want, just wrap the promiseTest
function call in setTimeout
.