我正在查看这个描述 JavaScript 中的文件遍历算法的要点
// ES6 version using asynchronous iterators, compatible with node v10.0+
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* walk(entry);
else if (d.isFile()) yield entry;
}
}
// Then, use it with a simple async for loop
async function main() {
for await (const p of walk('/tmp/'))
console.log(p)
}
我被(语言特性的,而不是作者的)将 async/await 塞进算法的每个缝隙的冲动所震惊。我不太了解 Node.js 的架构,但我认为严重异步特性背后有某种意图?对于主要是声明性过程 C/C++ 线程/进程模型的我来说,这非常令人困惑和新鲜。我想知道的不是“模型是什么”或“更好吗”,正如人们可能有的意见,而是“驱动异步性的想法是什么?”这是浏览器对响应能力的需求超过基于通用任务的效率的遗留问题吗?
我的问题是“为什么有这么多异步性?”。我不是在寻求意见,而是在寻找了解 Node.js 或 JavaScript 的历史和演变的人来解释其架构。
要点:https://gist.github.com/lovasoa/8691344
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号