Решение, которое я пришел с использованием ванили JavaScript async
await
и Promise
async function myFunc() {
const list = ["MainA:", "MainB:", "MainC:", "MainD:", "MainE:"];
let allPromises = [];
list.forEach(main => {
allPromises.push(runSubTasks(main));
});
console.log("allPromises before settle:", allPromises);
let data = await Promise.all(allPromises);
console.log("allPromises after settle:", allPromises);
console.log("resolved values inside allPromises:", data);
// All main tasks are done by this point
}
myFunc();
async function runSubTasks(main) {
const one = await asyncSubTask1(main, "");
const two = await asyncSubTask2(main, one);
return asyncSubTask3(main, two);
// or
// const three = await runTask3(main, two);
// return three;
}
function asyncSubTask1(main, sub) {
return new Promise((res, rej) => {
setTimeout(() => {
console.log(`${main}${sub}1`);
res(`${sub}1`);
}, Math.random() * 10000);
});
}
function asyncSubTask2(main, sub) {
return new Promise((res, rej) => {
setTimeout(() => {
console.log(`${main}${sub}2`);
res(`${sub}2`);
}, Math.random() * 10000);
});
}
function asyncSubTask3(main, sub) {
return new Promise((res, rej) => {
setTimeout(() => {
console.log(`${main}${sub}3`);
res(`${main}${sub}3`);
}, Math.random() * 10000);
});
}