Skip to content

Instantly share code, notes, and snippets.

@webber2408
Created July 7, 2020 04:30
Show Gist options
  • Save webber2408/4ab2e2476678e6a23fb1b0e8d5ba4306 to your computer and use it in GitHub Desktop.
Save webber2408/4ab2e2476678e6a23fb1b0e8d5ba4306 to your computer and use it in GitHub Desktop.
Asynchronous Iterations in JavaScript
let numArray = [5, 2];
let arrayOfPromise = [];
//Building array of promise
numArray.forEach((item) => {
arrayOfPromise = [...arrayOfPromise, new Promise((resolve, reject) => {
setTimeout(()=> {
resolve("Called after "+item+" seconds");
}, item*1000);
})]
});
(async () => {
for (element of arrayOfPromise){
element.then((res)=>{
console.log(res);
});
}
})();
/*
Called after 2 seconds
Called after 5 seconds
*/
//Waiting for each Promise using async / await
//Important: Notice the use of await within the for loop
(async () => {
for await (element of arrayOfPromise){
console.log(element)
}
})();
/*
Called after 5 seconds
Called after 2 seconds
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment