等待返回的异步映射函数Promise而不是value [英] Asynchronous map function that await's returns Promise instead of value

查看:71
本文介绍了等待返回的异步映射函数Promise而不是value的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码

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

但是不幸的是,它只是返回了一些承诺,因为没有等待map中的异步函数.我想知道是否有任何方法可以等待上面代码中的映射函数.

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.

推荐答案

尝试

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

这篇关于等待返回的异步映射函数Promise而不是value的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆