Skip to content

Instantly share code, notes, and snippets.

@kentcdodds
Created June 12, 2018 15:11
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kentcdodds/d0a20a03464bf86900af093a666c42db to your computer and use it in GitHub Desktop.
Save kentcdodds/d0a20a03464bf86900af093a666c42db to your computer and use it in GitHub Desktop.
Different mechanisms for making async work sequential.
// code for my devtip on 12 June 2018:
// https://www.youtube.com/watch?v=0wiM3jW1DVY&list=PLV5CVI1eNcJgCrPH_e6d57KRUTiDZgs0u
const loadFile = file => {
return new Promise(resolve => {
setTimeout(() => {
resolve(`contents of ${file}`)
}, 500)
})
}
const files = ['01.md', '02.md', '03.md', '04.md', '05.md']
const allPromises = files.map(file => loadFile(file))
Promise.all(allPromises).then(result => {
console.log('all', result)
})
let currentPromise = Promise.resolve([])
files.forEach(file => {
currentPromise = currentPromise.then(allContents => {
return loadFile(file).then(contents => {
allContents.push(contents)
return allContents
})
})
})
currentPromise.then(result => {
console.log('forEach', result)
})
files.reduce((previousPromise, file) => {
return previousPromise.then(allContents => {
return loadFile(file).then(contents => {
allContents.push(contents)
return allContents
})
})
}, Promise.resolve([])).then(result => {
console.log('reduce', result)
})
;(async () => {
const allContents = []
for (file of files) {
allContents.push(await loadFile(file))
}
console.log('async', allContents)
})()
@sudarshang
Copy link

sudarshang commented Jun 22, 2018

node 10 allows yet another variant

function* loadFiles() {
  for (file of files) {
    yield loadFile(file);
  }
}

(async () => {
  const allContents = [];
  for await (content of loadFiles()) {
    allContents.push(content);
  }
  console.log('for await', allContents);
})();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment