The documentation says the following:
allSettled
The method Promise.allSettled()
returns a promise that is resolved after all given promises have been resolved or rejected, with a array
of objects that describe the result of each promise.
That is, in your case it will not work the way you expect because its functions are not asynchronous.
To achieve the desired result you should use functions that return promises:
const executar = async (texto, ms) => {
await aguardar(ms);
console.log(texto);
};
const aguardar = ms => new Promise(resolve => setTimeout(resolve, ms));
(async () => {
console.time('Execução');
await Promise.allSettled([executar('primeiro', 50), executar('segundo', 10)]);
console.timeEnd('Execução');
})();
Note that in the example above I put a function aguardar
which aims to change the time of execution of the function, highlighting the difference of the executions.
Asynchronous functions
The statement async Function defines an asynchronous function, which returns an object AsyncFunction
.
You can also define asynchronous functions using a expression async function
.
When an asynchronous function is called, it returns a Promise
. When the asynchronous function returns a value, a Promise
will be solved with the value returned. When the asynchronous function throws an exception or some value, the Promise
will be rejected with the value launched.
An asynchronous function may contain an expression await
, which pauses the execution of the asynchronous function and waits for the resolution of the Promise
passed, and then resumes the execution of the asynchronous function and returns the solved value.
No, what I need is for several functions of my application to run at the same time, not a few more, some functions are simple things, but I want to run in parallel. I gave this function that I made an example because if I am correct I will be able to do the rest by myself, can take away the doubt, if this function is running in parallel?
– user210827
In Javascript nothing runs at the same time. Asynchronous execution is something else. To run something really parallel, only using Workers, but this is for specific cases. Are you not trying to make a premature optimization?
– bfavaretto
For explanation of the functioning of asynchronous functions see https://answall.com/a/16960
– bfavaretto