Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 941
Fluidbyte Avatar asked Sep 10 '12 21:09

Fluidbyte


1 Answers

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
    }

})();
like image 134
jfriend00 Avatar answered Oct 08 '22 16:10

jfriend00