Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.