Asynchronous map function that await's returns

2019-03-25 18:30发布

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.

2条回答
Anthone
2楼-- · 2019-03-25 18:36

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; });
}
查看更多
冷血范
3楼-- · 2019-03-25 18:37

try

async function addFiles(dir,tree) {
  const files = await readDir(dir)
  await Promise.all(files.map(async (name) => {await readDir(dir); return name;})
}
查看更多
登录 后发表回答