Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
    }

})();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...