Asynchronous map function that await's returns Promise instead of value

Zane Hitchcox picture Zane Hitchcox · May 3, 2016 · Viewed 12.7k times · Source

I have this code

async function addFiles(dir,tree) {
  return (await readDir(dir))
    .map(async (name) => {await readDir(dir); return name;})
}

but unfortunately, it just returns a bunch of promises, because there the async function in map is not waited upon. I'm wondering if there is any way to await the mapped function in the above code.

Answer

Sitian Liu picture Sitian Liu · May 3, 2016

try

async function addFiles(dir,tree) {
  const files = await readDir(dir)
  await Promise.all(files.map(async (name) => {await readDir(dir); return name;})
}