Created
June 12, 2018 15:11
-
-
Save kentcdodds/d0a20a03464bf86900af093a666c42db to your computer and use it in GitHub Desktop.
Different mechanisms for making async work sequential.
This file contains 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
// 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) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
node 10 allows yet another variant