8
In Javascript, we have the Promise.all
, that solves an array of promises in a single Promise
. This process is apparently parallel, since the promises are resolved at the same time, and not in a linear way.
Beyond the Promise.all
, other functions such as Promise.allSettled
and Promise.race
also have a similar behavior of executing promises "at the same time", solving in one Promise
.
But that’s really kind of parallelism in Javascript? How it really works?
An example that compares the promises solving themselves in a linear and parallel, respectively:
// Irá demorar 500ms para dobrar o número.
const double = (num) => new Promise((resolve) =>
setTimeout(() => resolve(num * 2), 500)
);
(async () => {
const doubles = [];
const start = Date.now();
for (let i = 1; i <= 5; i++) {
doubles.push(await double(i));
}
console.log(doubles);
console.log(`Finished in ${Date.now() - start}ms.`);
})();
const double = (num) => new Promise((resolve) =>
setTimeout(() => resolve(num * 2), 500)
);
(async () => {
const nums = Array.from({ length: 10 }).map((_, i) => i + 1);
const start = Date.now();
const doubles = await Promise.all(nums.map(double));
console.log(doubles);
console.log(`Finished in ${Date.now() - start}ms.`);
})();
Javascript is not multithread, so there is no parallelism (which is execution simultaneous). What happens is that the codes are executed alternately, as the callback of the
setTimeout
other things can be performed. The 1°await
says that the return of the function should be waited to then continue the loop, while the 2° creates the promises and then applies the wait, ie in 1° creates and expects the return of each promise before going next, in the other, the wait is applied after all promises are started and are already waiting– Costamilam