javascript - FileReader 异步读取方法是否会阻塞主线程?

标签 javascript browser filereader

我知道异步方法应该是非阻塞的。但我通常看到它们应用于诸如 fetch() 之类的外部操作。 即:在浏览器外部处理的内容。

但是 FileReader() API 又如何呢?文件处理是由浏览器完成的,对吗?

const reader = new FileReader();

reader.onload = (event) => {
  console.log(event.target.result);
};

reader.onerror = (event) => {
  console.log(event.target.result);
};


// **ONE** OF THE POSSIBLE METHODS BELOW

reader.readAsText(file);
reader.readAsArrayBuffer(file);
reader.readAsBinaryString(file);
reader.readAsDataURL(file);

问题

如果我读取 100Gb 文件,是否会在某个时刻阻塞我的主线程?我的意思是,即使它在运行之前等待调用堆栈为空,每当它处理一些大文件时,这是否会阻塞我的主线程?在这种情况下它是如何工作的?

无论答案是什么,它是否适用于运行最终由浏览器处理的异步操作的任何方法?

最佳答案

是的,它是“异步”。

数据硬盘/内存访问等将并行完成,这通常需要更长的时间,为此浏览器不需要阻塞主线程,这是基本的 I/O 操作。

实际reading and processing of the binary data无论您要求什么格式都必须完成 in parallel .

To run steps in parallel means those steps are to be run, one after another, at the same time as other logic in the standard (e.g., at the same time as the event loop). This standard does not define the precise mechanism by which this is achieved, be it time-sharing cooperative multitasking, fibers, threads, processes, using different hyperthreads, cores, CPUs, machines, etc. By contrast, an operation that is to run immediately must interrupt the currently running task, run itself, and then resume the previously running task.

当然,我们不能确定它是真正的并行性,因为硬件可能不支持并发,但从规范的 Angular 来看,它是异步的。

现在,读取 100GB 文件肯定会抛出一个错误,指出您没有足够的可用内存。如果您确实有足够的内存,那么您的计算机很可能会因如此大的数据 block 而受到影响。
同样,生成的数据通过 .result 属性发送回线程时也会占用内存。处理太大的数据可能会影响页面的性能。

关于javascript - FileReader 异步读取方法是否会阻塞主线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56522431/

相关文章:

apache - jmeter 中的浏览器缓存模拟?

mobile - iPhone 网站 - 但其他平台呢?

javascript - 使用 Cordova 文件插件读取文件

Java 将文件中的行与 String 进行比较

javascript - CSS Sprites - 如何让悬停按钮处于按下状态

javascript - 'withRouter' 已被导入但仍然出现 TypeError : Cannot read property 'push' of undefined

javascript - 如何使用 HTML 或 JavaScript 重定向到其他页面

javascript - Backbone 插入位置和移位模型

php - 一个 php 网络浏览器

java - 简单的纯java CSV读取和解析