Skip to content
Fix Code Error

Using async/await with a forEach loop

March 13, 2021 by Code Error
Posted By: Anonymous

Are there any issues with using async/await in a forEach loop? I’m trying to loop through an array of files and await on the contents of each file.

import fs from 'fs-promise'

async function printFiles () {
  const files = await getFilePaths() // Assume this works fine

  files.forEach(async (file) => {
    const contents = await fs.readFile(file, 'utf8')
    console.log(contents)
  })
}

printFiles()

This code does work, but could something go wrong with this? I had someone tell me that you’re not supposed to use async/await in a higher order function like this, so I just wanted to ask if there was any issue with this.

Solution

Sure the code does work, but I’m pretty sure it doesn’t do what you expect it to do. It just fires off multiple asynchronous calls, but the printFiles function does immediately return after that.

Reading in sequence

If you want to read the files in sequence, you cannot use forEach indeed. Just use a modern for … of loop instead, in which await will work as expected:

async function printFiles () {
  const files = await getFilePaths();

  for (const file of files) {
    const contents = await fs.readFile(file, 'utf8');
    console.log(contents);
  }
}

Reading in parallel

If you want to read the files in parallel, you cannot use forEach indeed. Each of the async callback function calls does return a promise, but you’re throwing them away instead of awaiting them. Just use map instead, and you can await the array of promises that you’ll get with Promise.all:

async function printFiles () {
  const files = await getFilePaths();

  await Promise.all(files.map(async (file) => {
    const contents = await fs.readFile(file, 'utf8')
    console.log(contents)
  }));
}
Answered By: Anonymous

Related Articles

  • How does PHP 'foreach' actually work?
  • For-each over an array in JavaScript
  • Angular: Can't find Promise, Map, Set and Iterator
  • How do I return the response from an asynchronous call?
  • Need help understanding this promise and handling the error
  • JavaScript ES6 promise for loop
  • Resolve promises one after another (i.e. in sequence)?
  • Any difference between await Promise.all() and…
  • Wait until all promises complete even if some rejected
  • How can I visualize an API mashup in Postman?
  • What's the best way to get the last element of an…
  • Why do I get an Unhandled Promise Rejection with…
  • How to detect FileReader load end?
  • Why is my asynchronous function returning Promise {…
  • Testing VueJS method inside of a promise which is…
  • convert streamed buffers to utf8-string
  • How to convert networkx node positions to…
  • Promise chaining unhandled promise
  • Attribute Error: 'list' object has no attribute 'split'
  • Get operating system info
  • How to aggregate values from a list and display in…
  • Delay content of test of Cloud Functions with Mocha
  • TypeScript / JavaScript: How to wrap a Promise…
  • Nodejs convert string into UTF-8
  • Node JS Promise.all and forEach
  • Backbone Collection.fetch gives me Uncaught…
  • How can I create a Promise in TypeScript from a union type
  • Unhandled Promise Rejection when trying to call…
  • Looking for Bluebird promise function "any" as series
  • Smart way to truncate long strings
  • Property or method "key" is not defined on the…
  • Binance WebSocket Order Book - depths change every time
  • postgresql and collation problem when importing
  • How to register a custom callback after Ember.RSVP.hash
  • python encoding utf-8
  • How are Ember's Promises related to Promises in…
  • Logging best practices
  • How to get UTF-8 working in Java webapps?
  • Ember 2, filter relationship models (hasMany,…
  • Use async await with Array.map
  • How can I access and process nested objects, arrays or JSON?
  • Promise.catch fails in IE11 with polyfills
  • How can we return data's from firebase queries with…
  • Changing PowerShell's default output encoding to UTF-8
  • How to use Backbone.Model.save() promise with validation
  • How to wait for a JavaScript Promise to resolve…
  • Using Ember (cli) how do I get an acceptance test to…
  • How to call an async function on button click in…
  • Why is my variable unaltered after I modify it…
  • how to make column bool data to be true with the…
  • Angular and Typescript: Can't find names - Error:…
  • How are variables in a call stack in JavaScript…
  • Casting to number from query fails. Node.js Express Mongoose
  • How to refactor Node.js code that uses…
  • Asynchronous Process inside a javascript for loop
  • Function return type depends on optional argument
  • Promise value not put into template after resolved
  • What is the difference between utf8mb4 and utf8…
  • Microsoft Excel mangles Diacritics in .csv files?
  • What is an IndexOutOfRangeException /…
  • What is a promise object?
  • Correct way to write loops for promise.
  • What is the scope of variables in JavaScript?
  • array prints empty in after pushing elements into it…
  • Handling errors in Promise.all
  • Item position in RecyclerView only changing when…
  • "Thinking in AngularJS" if I have a jQuery background?
  • Is there any JSON Web Token (JWT) example in C#?
  • So can't use weasyprint what is the best thing to do?
  • How to get WooCommerce order details
  • bootstrap-datepicker in dd/mm/yyyy - selected date…
  • Why do we need middleware for async flow in Redux?
  • Call async/await functions in parallel
  • How can I test if a function is returning a promise…
  • How to set new properties, or push to array with…
  • Struggling to await in for loop
  • Am I paranoid? "Brutally" big Polymer website after…
  • jest.fn() claims not to have been called, but has
  • Bluebird promise pattern when creator cannot resolve
  • Executing class instance method that is in an array…
  • NEXT.JS with persist redux showing unexpected behaviour
  • Weaseyprint, Cairo, Dajngo on Pythonanywhere 25MAY21…
  • How to remove element from array in forEach loop?
  • Saving a multi-dimensional list in a file Python
  • Wait for response from request before returning
  • then block executed before promise resolves/reject…
  • Programmatically generate url from path and params
  • Why does a match on covariant enum does not behave…
  • Can't upload files with Apollo-client GraphQL in…
  • Vue js vuecli3 application does not work in ie11…
  • How do you clear the SQL Server transaction log?
  • Access one dimensional array with array of array…
  • How can I use Promises in Aurelia?
  • How do I use arrays in C++?
  • How to sleep a process when using multiprocessing in…
  • Firebase cloud function onUpdate is triggered but…
  • invalid byte sequence for encoding "UTF8": 0x89…
  • Array.Sort doesn't work correctly in for{} loop
  • JS async/await doesn't wait for my functions to…
  • Aurelia with Typescript and async functions: this is…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Refused to display in a frame because it set ‘X-Frame-Options’ to ‘SAMEORIGIN’

Next Post:

What is the difference between the ‘COPY’ and ‘ADD’ commands in a Dockerfile?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error