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
}
})();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…