人们有时会提到下面的回调模式是异步的。
function beAsync(msg, cb){
cb(msg);
}
beAsync("a", function(msg){
console.log(msg);
});
console.log("b");
人们有时会说,beAsync
允许运行其余代码,然后在准备就绪时发生回调。
当我调用 beAsync
和真正的异步函数(例如 fs.readFile
)时,最初一定有一些代码同步运行,然后发生了一些事情允许 readFile
之后的代码允许运行其余代码。
我说的代表回调进入比 JavaScript 更低级别的循环的说法正确吗?
因此,对 beAsync 的修订将包括 setTimeout。
function beAsync(msg, cb){
setTimeout( function(){ cb(msg) }, 1);
}
那么 setTimeout 和 readFile 的内部结构可以与 JavaScript 所在的层进行对话吗? 与这个较低层对话是在 JavaScript 中实现非阻塞代码的唯一方法吗?
最佳答案
Speaking to this lower layer is the only way to achieve non-blocking code in JavaScript?
这有点正确。 Node 只是等式的一部分。框架本身大量使用线程来管理可能阻塞的事物,例如 IO。看看
When I call beAsync and real asynchronous functions like fs.readFile initially there must be some code that runs synchronously and then something happens that allows the code after readFile rest of the code is allowed is allowed to run.
这不是很详细,但从高层次上来说是正确的。每当您启动一些异步工作并为该方法提供回调时,就会完成一些工作来执行您的回调以及工作结果。
关于node.js - 我对 Node 中 'Non-blocking' 的理解是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8838734/