javascript - Utiliser async/await avec une boucle forEach

Mots clés : javascriptnode.jspromiseasync-awaitecmascript-2017javascript

meilleur 5 Réponses javascript - Utiliser async/await avec une boucle forEach

vote vote

98

async function printFiles () {   const files = await getFilePaths();    for (const file of files) {     const contents = await fs.readFile(file, 'utf8');     console.log(contents);   } } 
async function printFiles () {   const files = await getFilePaths();    await Promise.all(files.map(async (file) => {     const contents = await fs.readFile(file, 'utf8')     console.log(contents)   })); } 
vote vote

86

async function printFiles () {   const files = await getFilePaths()    for await (const contents of files.map(file => fs.readFile(file, 'utf8'))) {     console.log(contents)   } } 
vote vote

78

async function printFiles () {   const files = await getFilePaths();    await files.reduce(async (promise, file) => {     // This line will wait for the last async function to finish.     // The first iteration uses an already resolved Promise     // so, it will immediately continue.     await promise;     const contents = await fs.readFile(file, 'utf8');     console.log(contents);   }, Promise.resolve()); } 
vote vote

64

const { forEach } = require('p-iteration'); const fs = require('fs-promise');  (async function printFiles () {   const files = await getFilePaths();    await forEach(files, async (file) => {     const contents = await fs.readFile(file, 'utf8');     console.log(contents);   }); })(); 
vote vote

57

Array.prototype.forEachAsync = async function (fn) {     for (let t of this) { await fn(t) } }  Array.prototype.forEachAsyncParallel = async function (fn) {     await Promise.all(this.map(fn)); } 

Questions similaires