Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 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 Reply

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
    }

})();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...