Last active
March 2, 2022 12:18
-
-
Save franciscohanna92/3371b7d41ae88f0aaf708464f7e7d1e4 to your computer and use it in GitHub Desktop.
Execute array of async functions in order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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