繁体   English   中英

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

[英]If I make a function in javascript that contains only asynchronous functions, is the new function also asynchronous?

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

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

现在,如果我像这样五次调用foobar():

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

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

不,它将触发所有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/

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

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

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

foob​​ar内对异步函数的调用总数为10(5 * 2)。

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

当然,你可以建立一个限制器来限制你在相互之后快速射击foobar时的调用量......

        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()方法之后,异步方法是否都没有完成执行,所以将有十个异步方法正在执行。

暂无
暂无

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

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