node.js:while循环回调不能按预期工作 [英] node.js: while loop callback not working as expected

查看:590
本文介绍了node.js:while循环回调不能按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

知道当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循环15secs),只是THEN打印完成到控制台。据我所知,这是因为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");

所以我以为这将打印'DONE',15秒后。 'done sleeping',因为sleep()函数被调用,并被一个指向回调函数的指针。当这个函数工作时(while循环),最后一行将被执行(print'done')。 15秒后,当sleep()函数完成时,它调用给定的回调函数,然后打印'done sleeping'。

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是单线程的,这意味着一个简单的同时阻塞;没有请求/事件可以被处理,直到阻塞完成。回调函数不会神奇地解决这个问题,他们只是帮助传递自定义代码到一个函数。相反,使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆