简体   繁体   English

Javascript - 为什么这个代码会阻塞?

[英]Javascript - Why does this code blocks?

I Don't get why this code blocks. 我不明白为什么这个代码阻止。 I use nodejs async functions, but now I'm trying to figure out what's the essence of non-blocking programming, and how can I implement those. 我使用nodejs异步函数,但现在我想弄清楚非阻塞编程的本质是什么,以及如何实现它们。 This is the way I thought it would be, but Its still blocking. 这是我认为的方式,但它仍然阻塞。

   var async_func = function(x, func) {
        func(x+5);
    };

    setTimeout( async_func(5, function(number) {
        for (var x = 0; x < 1000000000; x++) {;}
        console.log(number);
    }), 3000);

    console.log("done");

Try: 尝试:

var async_func = function(x, func) {
    func(x+5);
};

setTimeout(function(){
    async_func(5, function(number) {
       console.log(number);
    });
}, 3000);

console.log("done");

(I also removed the unnecessary for (var x = 0; x < 1000000000; x++) {;} ) (我也删除了不必要for (var x = 0; x < 1000000000; x++) {;}

You should not call a function with arguments in setTimeout without making an anonymous or helper function... (If you really want to do it without setting another function check @Ian comments bellow.) 你不应该在没有匿名或帮助函数的情况下调用setTimeout中带有参数的函数...(如果你真的想这样做而不设置另一个函数,请检查@Ian comments below。)

If your function didn't had any arguments you could do setTimeout(async_func, 3000); 如果你的函数没有任何参数,你可以做setTimeout(async_func, 3000); but in this case the best thing is just to call it trough an anonymous function (or declaring a calling function above calling your function with those arguments. 但在这种情况下,最好的办法就是通过匿名函数调用它(或者在上面用这些参数调用函数来声明一个调用函数)。

This is a common mistake when using setTimeout() and when passing function references where you want to call a function with arguments. 这是使用setTimeout()以及在要使用参数调用函数的函数引用时传递的常见错误。 This line of code: 这行代码:

setTimeout( async_func(5, function(number) {

executes async_func() immediately and then passes it's return result (which is not a function) to setTimeout() and that is NOT what you want. 立即执行async_func()然后将它的返回结果(不是函数)传递给setTimeout() ,这不是你想要的。 You want to pass a function reference to setTimeout() so setTimeout() can call that function later like this: 您想要将函数引用传递给setTimeout()以便setTimeout()可以稍后调用该函数,如下所示:

var async_func = function(x, func) {
    func(x+5);
};

setTimeout( function() {
    async_func(5, function(number) {
        for (var x = 0; x < 1000000000; x++) {;}
        console.log(number);
    });
}, 3000);

console.log("done");    

or, sometimes it's easier to understand by making your timer callback function it's own separate function with no arguments. 或者,有时通过使您的计时器回调函数更容易理解它是自己的单独函数,没有参数。

function async_func(x, func) {
    func(x+5);
}

function timer_func() {
    async_func(5, function(number) {
        for (var x = 0; x < 1000000000; x++) {;}
        console.log(number);
    });
}

setTimeout(timer_func, 3000);

console.log("done");    

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

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