Junior — Middle
How do you organize the execution of multiple tasks of the same importance?
sobes.tech AI
Answer from AI
To organize the execution of multiple tasks of equal importance in Node.js, parallel or concurrent execution is usually used with asynchronous functions and promises. For example, you can use Promise.all to run multiple asynchronous operations simultaneously and wait for their completion.
Example:
const task1 = () => new Promise(resolve => setTimeout(() => resolve('Task 1 done'), 1000));
const task2 = () => new Promise(resolve => setTimeout(() => resolve('Task 2 done'), 500));
Promise.all([task1(), task2()])
.then(results => {
console.log(results); // ['Task 1 done', 'Task 2 done']
});
If there are many tasks and you need to control the number of tasks running simultaneously, you can use libraries like p-limit or implement a task queue. This helps distribute resources evenly and avoid overload.