简体   繁体   中英

JavaScript Loop and wait for function

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(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?

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.

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

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 async and await like this:

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
    }

})();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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