如果我在javascript中创建一个只包含异步函数的函数,那么新函数是否也是异步的?

时间:2011-12-29 07:44:06

标签: javascript asynchronous

例如,假设我创建了一个名为“foobar”的函数,而foobar内部则调用了异步函数。例如,它可能如下所示:

function foobar() {
    // asynchronous function here.
    // asynchronous function here.
}

现在,如果我像这样召唤foobar()五次:

foobar();
foobar();
foobar();
foobar();
foobar();

它一次只能触发两个异步函数吗?

5 个答案:

答案 0 :(得分:2)

不,它将触发所有10.它将触发前两个(异步),然后单个Javascript线程将从第一个调用返回并进入第二个调用,再调用两个等等。直到所有10个调用。例如:

var i = 0;
function foobar(){
    // Execute functions asynchronously by using setTimeout
    setTimeout(function(){ alert(++i); }, 0);
    setTimeout(function(){ alert(--i); }, 0);
}

foobar();
foobar();
foobar();
foobar();
foobar();
alert('This will ALWAYS alert first');

由于Javascript是单线程的,因此最后一个警报将始终首先发出警报,之后其他警报将根据计划以任何顺序发生。您可能会看到-5到5之间的任何数字被警告,但最后一个警报将始终为0。

http://jsfiddle.net/Paulpro/uJd44/

答案 1 :(得分:1)

异步函数的主要特征是它立即返回,稍后执行其工作,然后通常通过回调通知调用者其工作已完成。

因此,在您的示例中,对foobar()的五次调用将导致总共触发十个异步函数,因为所有这些函数将立即返回其调用者。

答案 2 :(得分:0)

我认为每次foobar()调用所有异步函数都会在内存中创建一个新副本

答案 3 :(得分:0)

foobar中对异步函数的调用总数为10(5 * 2)。

foobar中的函数是异步的,因此foobar将结束,而其他函数仍然很忙。然后,调用下一个foobar,触发另外两个异步函数等等。

当然,你可以建立一个限制器,以便在你彼此之后快速射击foobar时限制通话量......

答案 4 :(得分:0)

        foobar();  // It will invoke two asynchronous function and even if they are not   
                 //completely executed control will got to second/next foobar() method invocation
        foobar();  // Irrespective of whether first two asynchronous function have  
                  //completed or not this method will invoke two asynchronous functions  
                 // again. and next //foobar() method call will be executed

        foobar(); // Same continues
        foobar();
        foobar();

考虑是否在调用最后一个foobar()方法之后,异步方法都没有完成执行,因此将执行十个异步方法。