node.js:while 循环回调未按预期工作 [英] node.js: while loop callback not working as expected
问题描述
知道虽然 Node.js 是异步工作的,写这样的东西:
Knowing that while Node.js is working asynchronously, writing something like this:
function sleep() {
var stop = new Date().getTime();
while(new Date().getTime < stop + 15000) {
;
}
}
sleep();
console.log("done");
...将调用 sleep(),在 while 循环期间(15 秒)阻塞服务器,然后将完成"打印到控制台.据我了解,这是因为 Node.js 只允许 JavaScript 访问主线程,因此这种东西会停止进一步的执行.
...would call the sleep(), block the server for the duration of the while loop (15secs) and just THEN print "done" to the console. As far as I understand, this is because Node.js is giving JavaScript only access to the main thread, and therefore this kidn of thing would halt further execution.
所以我理解解决这个问题的方法是使用回调:
So I understand the solution to this is to use callbacks:
function sleep(callback) {
var stop = new Date().getTime();
while(new Date().getTime() < stop + 15000) {
;
}
callback();
}
sleep(function() {
console.log("done sleeping");
});
console.log("DONE");
所以我认为这会在 15 秒后打印完成".'done sleep',因为 sleep() 函数被调用并被传递一个指向回调函数的指针.当这个函数运行时(while 循环),最后一行将被执行(print 'done').15 秒后,当 sleep() 函数完成时,它调用给定的回调函数,然后打印done sleep".
So I thought this would print 'DONE' and after 15 secs. 'done sleeping', since the sleep() function gets called and is handed a pointer to a callback function. While this function is working (the while loop), the last line would be executed (print 'done'). After 15 seconds, when the sleep() function finishes, it calls the given callback function, which then prints 'done sleeping'.
显然我在这里理解错了,因为上述两种方式都阻塞了.有大佬可以解释一下吗?
Apparently I understood something wrong here, because both of the above ways block. Can anybody clarify please?
提前致谢,Slagjoeyoco
Thanks in advance, Slagjoeyoco
推荐答案
Javascript 和 node.js 是单线程的,这意味着一个简单的 while
块;在 while
块完成之前,不能处理任何请求/事件.回调并不能神奇地解决这个问题,它们只是帮助将自定义代码传递给函数.相反,使用 process.nextTick
进行迭代,这将给您本质上相同的结果,但也为要处理的请求和事件留出空间,即它不会阻塞:
Javascript and node.js are single threaded, which means a simple while
blocks; no requests/events can be processed until the while
block is done. Callbacks don't magically solve this problem, they just help pass custom code to a function. Instead, iterate using process.nextTick
, which will give you esentially the same results but leaves space for requests and events to be processed as well, ie, it doesn't block:
function doSleep(callback) {
var stop = new Date().getTime();
process.nextTick(function() {
if(new Date().getTime() < stop + 15000) {
//Done, run callback
if(typeof callback == "function") {
callback();
}
} else {
//Not done, keep looping
process.nextTick(arguments.callee);
}
});
}
doSleep(function() {
console.log("done sleeping");
console.log("DONE");
});
这篇关于node.js:while 循环回调未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!