首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >async for循环会导致函数静默终止

async for循环会导致函数静默终止
EN

Stack Overflow用户
提问于 2020-11-18 16:24:16
回答 1查看 48关注 0票数 2

你好,我正在尝试理解下面这段代码中发生了什么:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import fs from "fs";
import util from "util";
import split2 from "split2";

async function main() {
    const files = await fs.promises.readdir("..");
    for (const f of files) {
        const s = fs.createReadStream("../" + f);
        const ss = s.pipe(split2());
        s.on("error", (err) => {
            console.log(err);
        });
        for await (const l of ss) {
        }

        console.log(f);
    }
    console.log("Returning");
    return "Done";
}
main();

它基本上读取目录中的每个文件并遍历每个文件的行(通过使用for await语法将可读流通过管道传输到split2库中。问题是,当文件确实是一个目录时,createReadStream会失败(随后没有任何内容通过管道传输到下游)。奇怪的是,似乎是一个单一的错误导致main函数静默退出,并且在错误之前只显示了几个文件名。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
.gitignore
app.js
[Error: EISDIR: illegal operation on a directory, read] {
  errno: -21,
  code: 'EISDIR',
  syscall: 'read'
}

如果我只是注释await for循环,我会得到以下输出。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
.gitignore
app.js
business
components
config
env.skeletron
node_modules
package-lock.json
Returning
[Error: EISDIR: illegal operation on a directory, read] {
  errno: -21,
  code: 'EISDIR',
  syscall: 'read'
}
[Error: EISDIR: illegal operation on a directory, read] {
  errno: -21,
  code: 'EISDIR',
  syscall: 'read'
}
[Error: EISDIR: illegal operation on a directory, read] {
  errno: -21,
  code: 'EISDIR',
  syscall: 'read'
}
[Error: EISDIR: illegal operation on a directory, read] {
  errno: -21,
  code: 'EISDIR',
  syscall: 'read'
}
[Error: EISDIR: illegal operation on a directory, read] {
  errno: -21,
  code: 'EISDIR',
  syscall: 'read'
}
[Error: EISDIR: illegal operation on a directory, read] {
  errno: -21,
  code: 'EISDIR',
  syscall: 'read'
}
[Error: EISDIR: illegal operation on a directory, read] {
  errno: -21,
  code: 'EISDIR',
  syscall: 'read'
}
[Error: EISDIR: illegal operation on a directory, read] {
  errno: -21,
  code: 'EISDIR',
  syscall: 'read'
}

这确实是完整的文件列表,单个错误并没有停止外部循环。我在一台Ubuntu机器上用node v14.0.0运行它。知道是怎么回事吗?我真的迷路了:-D

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-18 16:39:07

您没有在for await (const l of ss) {...}循环中处理错误。当你试图在一个目录上运行它时,你的for await循环将会拒绝,因为你不能捕获或处理这个拒绝,所以包含的async函数也会拒绝,程序也会停止。

您可以尝试在for await循环周围放置一个try/catch,看看是否有效。但是,我在streams的for await特性中发现了许多bug,甚至提交了一些bug。如果打开文件时出错或读取文件时出错,就会出现bug,所以这个特性有bug,因此我决定不在我的代码中使用它。

另外,请注意,由于不能从嵌套的事件处理程序中拒绝async函数,因此没有一种很好的方法来从error事件传回错误。总体而言,流及其事件与基于promise的编程不能很好地混合。有一些方法可以简化一些流事件,但要让流与promises一起很好地工作,这是一个正在进行的工作。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64897131

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文