How to Array.map chain off of async await?

为君一笑 提交于 2019-12-13 07:57:38

问题


How can I run Array.map off of an await?

const CLASS_PATH = 'User/matt/Github/project';
const PACKAGE_JSON = 'package.json';

const walk = async path => {
  let dirs = [];
  for (const file of await readdir(path)) {
    if ((await stat(join(path, file))).isDirectory()) {
      dirs = [
        ...dirs,
        file,
      ];
    }
  }
  return dirs;
};


async function main() {
  const packagePaths = await walk(CLASS_PATH)
        .map(pkgName => join(CLASS_PATH, pkgName, PACKAGE_JSON));

}
main();

回答1:


Brackets can always be used to change operator predescendence:

 (await walk(CLASS_PATH)).map(/*...*/)



回答2:


You can also use Promise. So in your case:

const packagePaths = await Promise.all(walk(CLASS_PATH).map(async (item): Promise<number> => {
    await join(CLASS_PATH, pkgName, PACKAGE_JSON);
}));

The Promise.all(iterable) method returns a promise that resolves when all of the promises in the iterable argument have resolved, or rejects with the reason of the first passed promise that rejects.



来源:https://stackoverflow.com/questions/56193922/how-to-array-map-chain-off-of-async-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!