'Promise doesn't execute asynchronously [duplicate]
I have been testing promises on node.js in the following program:
const areallylongprocesspromise = new Promise((resolve, reject) => {
let buff = 0;
for (let i = 0; i < 1000000000; i++)
{
if ((i % 73829) === 0) buff++;
}
if (buff > 10) resolve(buff);
else reject(buff);
});
areallylongprocesspromise.then((resolved) =>
{
console.log("Resolved: ", resolved);
})
.catch((rejected) => {
console.log("Rejected: ", rejected);
});
console.log("Waiting for execution to finish up");
The expected output is:
Waiting for execution to finish up
Resolved: 13545
However, the first statement, "waiting... up" doesn't get logged until the promise finishes execution, at which point both the statements get logged simultaneously. I'm new to the concept of promises, so I don't know what is going on here. Why is the promise holding up the execution of the rest of the code? Any help would be appreciated.
Solution 1:[1]
The code inside the Promise is not executed when you call .then, it is executed when you define the Promise itself - try just to log something at the beginning of the function:
const areallylongprocesspromise = new Promise((resolve, reject) => {
console.log('start');
...
});
Since your code is synchronous, it holds the execution of the code by definition.
Solution 2:[2]
That happens because NodeJS and Javascript, despite allowing I/O async calls, they form single-threaded applications
It means that when the CPU is computing
for (let i = 0; i < 1000000000; i++)
{
if ((i % 73829) === 0) buff++;
}
It does not do anything else.
If you use for example setTimeout it works as expected because it creates an async timer that works as an I/O operation
const areallylongprocesspromise = new Promise((resolve, reject) => {
let buff = 0;
for (let i = 0; i < 1000000000; i++)
{
if ((i % 73829) === 0) buff++;
}
setTimeout(()=> {
if (buff > 10) resolve(buff);
else reject(buff);
}, 1000)
});
areallylongprocesspromise.then((resolved) =>
{
console.log("Resolved: ", resolved);
})
.catch((rejected) => {
console.log("Rejected: ", rejected);
});
console.log("Waiting for execution to finish up");
This timer is useless here, just to show you how I/O async calls do work. That timer could represent for example reading a file, connecting to a DB or fetching an image from the internet, they are all I/O operations.
That's the magic of NodeJS, despite being single-threaded it does not block the code for I/O operations.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | moonwave99 |
| Solution 2 |
