问题
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