简体   繁体   English

如何用JavaScript编写非阻塞回调?

[英]How to write a non-blocking callback in Javascript?

Here is some code I am trying : 这是我正在尝试的一些代码:

startTask();

function startTask(){
    console.log('startTask enter');
    startLongTask(1, function(){
        console.log('long task complete');
    });
    console.log('startTask exit');
}

function startLongTask(i, callback) {
    while (i++ < 10000){
        console.log(i);
    }
    callback();
}

And here is the output (omitting the large series on numbers): 这是输出(省略数字上的大数列):

startTask enter
2
3
4
5
6
7
8
9
10
long task complete
startTask exit

As evident, if I have a long running operation, it's synchronous. 显而易见,如果我运行了很长时间,那么它是同步的。 It's like having startLongTask inline in startTask . 这就像在startTaskstartLongTask在线。 How do I fix this callback to be non-blocking. 我如何解决此回调是非阻塞的。 The output I expect is : 我期望的输出是:

startTask enter
startTask exit
2
3
4
5
6
7
8
9
10
long task complete

Javascript-only code does not have the ability to create new asynchronous operations in pure JS because the V8 interpreter in node.js does not give you full-fledged threads. 纯Javascript代码无法在纯JS中创建新的异步操作,因为node.js中的V8解释器无法为您提供完整的线程。

Libraries such as the fs module in node.js get their async behavior from native operations (outside of the JS/V8 world) and they interface to the JS engine with an async interface. 诸如node.js中的fs模块之类的库从本机操作(在JS / V8世界之外)获得异步行为,并通过异步接口与JS引擎接口。

That said, there are ways you can run operations in the background in node.js by using some non-JS code. 也就是说,有一些方法可以通过使用一些非JS代码在node.js中在后台运行操作。 You can start another process, you can use a variety of add-on modules that support other threads of execution, etc... All of these will go outside of pure node.js Javascript in order to offer an async interface. 您可以开始另一个过程,可以使用支持其他执行线程的各种附加模块,等等。所有这些都将在纯node.js Javascript之外,以提供异步接口。

If your task can be broken into short chunks, you can also simulate an asynchronous operation by doing small amounts of work on successive timers (this is a common work-around in the browser too). 如果您的任务可以分成几小段,您还可以通过在连续的计时器上进行少量工作来模拟异步操作(这也是浏览器中的常见解决方法)。

You can use a timeout function with 0 milliseconds delay. 您可以使用具有0毫秒延迟的超时功能。 Any functions in the timeout will be pushed to the end of the execution thread. 超时中的所有函数都将被推送到执行线程的末尾。 eg 例如

startTask();

function startTask(){
    console.log('startTask enter');
    setTimeout(function(){
        startLongTask(1, function(){
            console.log('long task complete');
        })
    }, 0);
    console.log('startTask exit');
}

function startLongTask(i, callback) {
    while (i++ < 100){
        console.log(i);
    }
    callback();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM