【发布时间】:2022-02-18 17:49:24
【问题描述】:
我读到fs.readFile 是一个异步操作,读取发生在主线程之外的单独线程中,因此主线程执行不会被阻塞。所以我想试试下面的东西
// reads take almost 12-15ms
fs.readFile('./file.txt', (err, data) => {
console.log('FIRST READ', Date.now() - start)
const now = Date.now()
fs.readFile('./file.txt', (err, data) => {
// logs how much time it took from the beginning
console.log('NESTED READ CALLBACK', Date.now() - start)
})
// blocks untill 20ms more, untill the above read operation is done
// so that the above read operation is done and another callback is queued in the poll phase
while (Date.now() - now < 20) {}
console.log('AFTER BLOCKING', Date.now() - start)
})
我正在父 fs.readFile 调用的回调中进行另一个 fs.readFile 调用。我期望的是日志NESTED READ CALLBACK 必须在AFTER BLOCKING 之后立即到达,因为读取必须在单独的线程中异步完成
结果日志NESTED READ CALLBACK 在AFTER BLOCKING 调用后15 毫秒出现,表明当我在while 循环中阻塞时,异步读取操作不知何故从未发生。顺便说一句,while 循环是用来模拟一些需要 20 毫秒才能完成的任务
这里到底发生了什么?还是我在这里遗漏了一些信息?顺便说一句,我正在使用 Windows
【问题讨论】:
标签: node.js express asynchronous async-await