2
I’m studying the concepts of asymchronism, I know that Node.js is single-threaded and that for some types of task he delegates the same to the libuv
(which has 4 threads by default) and others for the manager itself threads operating system. However, when testing a code snippet using multiple calls from setTimeout
the console.time()
returns 1 second for all of them. The setTimeout
runs in parallel?
What I understood about the Event loop is that it goes "stacking" asynchronous tasks and performs them in sequence, but I don’t understand why several setTimeout
scheduled to run after 1 second are returned at the same time.
Code snippet:
function sum(a, b) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(a + b)
}, 1000)
})
}
console.time('start')
Promise.all([
sum(1, 2),
sum(3, 5),
sum(3, 5),
sum(3, 5),
sum(3, 5),
sum(3, 5),
sum(3, 5),
]).then(res => {
console.timeEnd("start")
})
Exit:
start: 1004.434ms
This answers your question? It would be "Promise.all" (and other similar methods) an example of Javascript parallelism?
– Luiz Felipe
thanks, but generated more doubts
– Thiago
:Q Are you talking about this linked question or the answer? If this is the last one, try to explain why so I can see if I can give more details or recap. :-)
– Luiz Felipe
was the question linkada rs
– Thiago