JavaScript 循环并等待函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12359450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:00:42  来源:igfitidea点击:

JavaScript Loop and wait for function

javascriptjqueryarraysfunctionloops

提问by Fluidbyte

I have a simple single-dimension array, let's say:

我有一个简单的单维数组,让我们说:

fruits = ["apples","bananas","oranges","peaches","plums"];

I can loop through with with $.each()function:

我可以用$.each()函数循环:

$.each(fruits, function(index, fruit) {  
   showFruit(fruit);
});

but I'm calling another function which I need to finish before moving on to the next item.

但我正在调用另一个函数,在继续下一项之前需要完成该函数。

So, if I have a function like this:

所以,如果我有这样的功能:

function showFruit(fruit){
    $.getScript('some/script.js',function(){
        // Do stuff
    })
}

What's the best way to make sure the previous fruit has been appended before moving on?

在继续之前确保已附加先前的水果的最佳方法是什么?

回答by jfriend00

If you want one fruit to be appended before you load the next one, then you cannot structure your code the way you have. That's because with asynchronous functions like $.getScript(), there is no way to make it wait until done before execution continues. It is possible to use a $.ajax()and set that to synchronous, but that is bad for the browser (it locks up the browser during the networking) so it is not recommended.

如果您希望在加载下一个之前附加一个水果,那么您就无法按照现有方式构建代码。那是因为对于像 那样的异步函数$.getScript(),没有办法让它等到完成后再继续执行。可以使用 a$.ajax()并将其设置为同步,但这对浏览器不利(它会在联网期间锁定浏览器),因此不推荐使用。

Instead, you need to restructure your code to work asynchronously which means you can't use a traditional foror .each()loop because they don't iterate asynchronously.

相反,您需要重构代码以异步工作,这意味着您不能使用传统for.each()循环,因为它们不会异步迭代。

var fruits = ["apples","bananas","oranges","peaches","plums"];

(function() {
    var index = 0;

    function loadFruit() {
        if (index < fruits.length) {
            var fruitToLoad = fruits[index];
            $.getScript('some/script.js',function(){
                // Do stuff
                ++index;
                loadFruit();
            });
        }
    }
    loadFruit();

})();

In ES7 (or when transpiling ES7 code), you can also use asyncand awaitlike this:

在 ES7 中(或在转译 ES7 代码时),你也可以像这样使用asyncawait

var fruits = ["apples","bananas","oranges","peaches","plums"];

(async function() {
    for (let fruitToLoad of fruits) {
        let s = await $.getScript('some/script.js');
        // do something with s and with fruitToLoad here
    }

})();

回答by JasonFruit

Javascript in browsers is single-threaded. It will not continue until the function it called returns. You don't need to check.

浏览器中的 Javascript 是单线程的。它不会继续,直到它调用的函数返回。你不需要检查。