Created
July 7, 2020 04:30
-
-
Save webber2408/4ab2e2476678e6a23fb1b0e8d5ba4306 to your computer and use it in GitHub Desktop.
Asynchronous Iterations in JavaScript
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
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