DEV Community

loading...

Discussion on: Modern JS, when to use map or for?

Collapse
voraciousdev profile image
David R. Myers

I think it's important to note that the last example is slightly different than the first in that the wrapping function runFiles will not actually wait for the promises to resolve. You could always prepend the Promise.all call with an await, but in this instance, I think you might not really need await at all. In my experience, await is just syntactic sugar for Promise chaining. It's only necessary if you need synchronous steps in your asynchronous function. Your example could just be written as this:

const runFiles = (files) => {
 return Promise.all(files.map((file) => {
    const query = fs.readFileSync(file, "utf-8");

    return client.query(query);
 });
}

This gives you some flexibility, because you aren't forcing any Promises to resolve before moving on to the next Promise. In a consuming function, you now have two options.

const someFunction = async (files) => {
  // wait for runFiles to resolve all promises
  await runFiles(files)

  // or just allow it to run in the background
  runFiles(files)
}
Collapse
altneko profile image
NekoAlt Author

Wow, many thanks for your reply!

This way of doing things is new to me, and you're opening my eyes to think outside the single threaded box.

I will definitely try this approach, since it's more flexible.