Execute functions in an array sequentially
const processes = [process1, process2, process3];
// Define a function that returns a promise for each process
function process1() {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Process 1 completed");
resolve();
}, 1000);
});
}
function process2() {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Process 2 completed");
resolve();
}, 2000);
});
}
function process3() {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Process 3 completed");
resolve();
}, 3000);
});
}
// Use reduce to chain the promises and execute the processes sequentially
processes.reduce((promiseChain, currentProcess) => {
return promiseChain.then(() => currentProcess());
}, Promise.resolve())
.then(() => {
console.log("All processes completed");
});
Generates functions that depend on values in Array
const get_func(wait_time) => {
const f = () => {
return new Promise((resolve) => {
setTimeout(() => {
console.log(wait_time);
resolve();
}, wait_time);
}
return f
}
const function_array = [200, 300, 100, 500].map(element => {
return get_func(element)
}).reduce((promiseChain, currentProcess) => {
return promiseChain.then(() => currentProcess());
}, Promise.resolve())
.then(() => {
console.log("All processes completed");
});