Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 777
Zane Hitchcox Avatar asked May 02 '16 22:05

Zane Hitchcox


2 Answers

try

async function addFiles(dir,tree) {
  const files = await readDir(dir)
  await Promise.all(files.map(async (name) => {await readDir(dir); return name;})
}
like image 91
Sitian Liu Avatar answered Sep 17 '22 20:09

Sitian Liu


If you're using bluebird you can use this cleaner, shorter syntax with Promise.map

async function addFiles(dir, tree) {
  const files = await readDir(dir);
  return Promise.map(files, async (name) => { await readDir(dir); return name; });
}
like image 42
gafi Avatar answered Sep 20 '22 20:09

gafi