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

如果我在javascript中创建一个只包含异步函数的函数,那么新函数也是异步的吗?,javascript,asynchronous,Javascript,Asynchronous,例如,假设我创建了一个名为“foobar”的函数,foobar内部是对异步函数的调用。例如,它可能如下所示: function foobar() { // asynchronous function here. // asynchronous function here. } foobar(); foobar(); foobar(); foobar(); foobar(); 现在,如果我像这样调用foobar()五次: function foobar() { // a

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

function foobar() {
    // asynchronous function here.
    // asynchronous function here.
}
foobar();
foobar();
foobar();
foobar();
foobar();
现在,如果我像这样调用foobar()五次:

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

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


因此,在您的示例中,对
foobar()
的五次调用将导致总共触发十个异步函数,因为它们都将立即返回到调用方。

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

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

foobar中的函数是异步的,因此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()
方法之后,异步方法中是否没有一个已经完成执行,因此将有十个异步方法正在执行

不,它将全部启动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


您能描述一下您提到的这个节流器吗?您可以在这里使用一个现有的节流器(也可以在没有JQuery的情况下使用),或者在这里阅读有关它的内容,但一般来说,节流器使用setTimeout()函数来确保任何给定的函数只每隔这么多毫秒执行一次。很有趣!为什么在第一个警报和所有其他警报之间会有延迟?而且,您可以通过将任何函数放入setTimeout这样的方式使其异步?@trusktr这与警报的阻塞性质有关。我不知道为什么浏览器需要一点时间才能意识到它不再被阻塞,并且可以切换线程,但它似乎是。如果将警报更改为
console.log()
,则不会出现这种情况(但执行速度非常快,几乎可以肯定线程会按其发生的顺序进行调度,因此您将看到1 0 1 0 1 0 1 0作为输出。@trusktr是的,您可以使用类似的setTimeout使它们异步。是的,您可以注意到setTimeout内的函数将从全局范围(即“this”)触发除非执行func.bind(someContext)(),否则将引用窗口);其中“this”将引用函数func中的someContext。有关详细信息,请参阅