Skip to content

Instantly share code, notes, and snippets.

@franciscohanna92
Last active March 2, 2022 12:18
Show Gist options
  • Save franciscohanna92/3371b7d41ae88f0aaf708464f7e7d1e4 to your computer and use it in GitHub Desktop.
Save franciscohanna92/3371b7d41ae88f0aaf708464f7e7d1e4 to your computer and use it in GitHub Desktop.
Execute array of async functions in order
/*
Given an array of async functions, execute them in order.
*/
// Our async functions array
const asynFunctions = [
() => new Promise((resolve) => setTimeout(() => resolve("1"), 200)),
() => new Promise((resolve) => setTimeout(() => resolve("2"), 300)),
() => new Promise((resolve) => setTimeout(() => resolve("3"), 100))
]
// Expected console print: 1, 2, 3
/*
The following doesn't work, because forEach will create an independent async function for each member of the array,
and the order of execution bewteen these functions can't be controlled.
*/
const executorForEach = (asynFunctions) => {
asynFunctions.forEach(async (fn) => {
console.log(await fn());
});
};
/*
The solution is to use for..of in the executor function, and define this function as async.
In this case, a single async function is defined and each function of the array is awaited before moving on to the next one.
*/
const executorForOf = async (asyncFunctions) => {
for(const fn of asyncFunctions) {
console.log(await fn())
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment