JavaScript的循环,待功能 [英] JavaScript Loop and wait for function

查看:90
本文介绍了JavaScript的循环,待功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

我可以循环直通用。每$()函数:

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

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

但我打电话给另外一个功能,我需要移动到下一个项目之前完成。

but I'm calling to 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
    })
}

什么是确保previous水果所具有的运动之前被追加的最佳方式?

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

推荐答案

如果您希望您加载下一个之前一水果附加,那么你就不能构建你的code你的方式。这是因为像 $异步函数。getScript加入(),有没有办法让它等到继续执行之前完成。有可能使用一个 $。AJAX()并设置为同步,但是这是不好的浏览器(它的网络中锁定了浏览器),所以它是不推荐使用。

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.

相反,你需要调整你的code到异步工作,这意味着你不能用传统的。每次( )循环,因为它们不异步迭代。

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();

})();

这篇关于JavaScript的循环,待功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆