Skip to content

Instantly share code, notes, and snippets.

@fraserxu
Last active February 20, 2020 03:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fraserxu/52483da27efe1f2b0972623dd770c499 to your computer and use it in GitHub Desktop.
Save fraserxu/52483da27efe1f2b0972623dd770c499 to your computer and use it in GitHub Desktop.
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