i've been searching, trying and i'm now hitting my head against the wall! Sounds like something simple but can't get ahead of it! Tried .each, .map, deferred, promise and some others but nothing worked.
So i thought i could ask here: For each element in an array, i need to call a function, wait for it to complete, move to next element and call the same function again.
function del(value) {
//do some stuff taking random time
console.log(value);
}
function asd() {
var arr = ["one", "two", "three", "four"];
$.each(arr, function(key, value) {
del(value);
});
}
$(function() {
$("a").click(function() {
asd();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#">test</a>
I wanna make sure i get "one", "two", "three", "four" in the right order. At the moment i sometimes get "three", "one", "two", "four"!
Thanks in advance, Regards
I think it is not the loop or order of the array it s the //do some stuff taking random time
I am assuming it is an async call most likely a ajax call. I handle this situation with the below code;
var arr = ["one", "two", "three", "four"];
function del(arrayParam) {
var item = arrayParam.shift(); //gets first item and removes it from the array
if (item) {
$(/*your ajax call*/).success(function() {
del(arrayParam); /*re call function*/
});
}
else {
// you are don with the array show message/alert etc
}
}
// and some how call the first call might be a button click etc.
del(arrayParam);