免责声明:我正在努力学习,所以问题可能是微不足道的;任何关于如何更好地做同样的事情的 comments 都是受欢迎的,但我需要理解潜在的概念.
我更像是一名Python程序员,所以async
/await
比较熟悉,而Promise则是一个相当新的概念.
我有一个简单的Node.js程序,它扫描一个子目录并处理文件名:
const chalk = require('chalk');
const ProgressBar = require('progress');
const fs = require('fs');
const path = require('path');
async function* walk(dir) {
for await (const d of await fs.promises.opendir(dir)) {
const entry = path.join(dir, d.name);
if (d.isDirectory()) yield* await walk(entry);
else if (d.isFile()) yield entry;
}
}
async function scan(cb) {
var docs = [];
for await (const p of walk('docs')) {
if (p.endsWith('.md')) {
console.log(p);
docs.push(p);
}
}
docs.sort();
if (cb)
cb(docs);
}
async function inspect(docs) {
const bar = new ProgressBar(':bar', { total: docs.length });
for (f in docs) {
if (bar.curr === 0) {
console.log(chalk.green('starting...'));
}
bar.tick();
// do other work and (possibly) modify `docs` array
if (bar.complete) {
console.log(chalk.green('done.'));
}
}
// pass docs to next stage
}
scan(inspect)
由于链将比这长得多(我需要读取文件、根据内容对它们进行排序、构建TOC等),我想修改它以使用类似于以下内容的promise :
scan('/my/dir/to/scan')
.then(inspect)
.then(generate, `/path/to/target/file/`)
.catch(printError)
但我找不到方法(我看到了关于这个问题的几个答案,但我找不到我的问题的真正答案).