Skip to content

Instantly share code, notes, and snippets.

@tmcgann
Created July 6, 2020 21:54
Show Gist options
  • Select an option

  • Save tmcgann/c6e731603a636fa6f12c714a050ff83b to your computer and use it in GitHub Desktop.

Select an option

Save tmcgann/c6e731603a636fa6f12c714a050ff83b to your computer and use it in GitHub Desktop.
Two different ways to process asynchronous requests serially without the use of convenient library like async (https://caolan.github.io/async/v3/docs.html#eachSeries).
(async function () {
// Setup
const values = [1, 2, 3]
const makeTimestamp = () => Math.round(Date.now() / 1000)
const request = (value, time = 1000) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(value)
}, time)
})
}
// async/await serial reduction
const result = await values.reduce(async (prev, value) => {
const collection = await prev
console.log(`START ${value}:`, makeTimestamp())
collection.push(await request(value))
console.log(`END ${value}:`, makeTimestamp())
return collection
}, (async () => [])())
console.log(`result:`, result)
// promise-based serial reduction
const promise = values.reduce((prev, value) => {
return prev.then(collection => {
console.log(`START ${value}:`, makeTimestamp())
return request(value).then(result => {
collection.push(result)
console.log(`END ${value}:`, makeTimestamp())
return collection
})
})
}, Promise.resolve([]))
promise.then(result => {
console.log(`result:`, result)
})
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment