Last active
February 20, 2020 03:46
-
-
Save fraserxu/52483da27efe1f2b0972623dd770c499 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const array = [1, 2, 3, 4, 5] | |
const fetchData = i => { | |
console.log(`fetching ${i}...`) | |
return new Promise(resolve => | |
setTimeout(() => { | |
console.log(`finished ${i}`) | |
resolve() | |
}, 1000) | |
) | |
} | |
const generateRequests = async () => { | |
// for await ..of execute async request in series | |
// will only start the next async request after the previous one finishes | |
for await (let i of array) { | |
await fetchData(i) | |
} | |
// works the same way as for...of | |
for (let i of array) { | |
await fetchData(i) | |
} | |
// Promise.all will start all the async request in parallel | |
return Promise.all(array.map(i => fetchData(i))) | |
// UnhandledPromiseRejectionWarning: TypeError: undefined is not iterable | |
return Promise.all(array.forEach(i => fetchData(i))) | |
// done will be called before all the requests finsih | |
return array.map(i => fetchData(i)) | |
return array.forEach(i => fetchData(i)) | |
} | |
;(async () => { | |
console.log('start') | |
await generateRequests() | |
console.log('done') | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Related reads: