I have an array which is filled asynchronous and contains 28 items. I want to wait until the array is filled with all items.
function checkIfFinished(){
return(Results.length >= 28);
}
var isfinished = false;
while(isfinished){
if(checkIfFinished()){
returnResults();
isfinished = true;
}
else
//Wait 100ms
}
Well, but in Javascript there is no wait function! I tried it with setTimeout, but I don't know how to insert it... I just get errors with too much recursion and stuff :D
Thank you!
To use Javascript promises in a for loop, use async / await . This waits for each promiseAction to complete before continuing to the next iteration in the loop.
The array methods are not async functions. They are normal functions. So when we pass an async function as a callback, It will not invoke the async callback function with await.
We have to call the async function from another function which can be asynchronous or synchronous (We can pass the array or choose to declare the array in the async function itself) and then return the array from the async function. The basic approach is to include a try-catch block.
Try:
var timeout = setInterval(function() {
if(checkIfFinished()) {
clearInterval(timeout);
isFinished = true;
}
}, 100);
This will call your check-function every 100 ms until checkIfFinished() gives true back to you.
If you're using jQuery 1.5+, this sounds like a perfect opportunity to use deferred objects and promises in your code. I'm assuming that you're using AJAX calls to populate your array.
In a nutshell, something like this should work for you:
$(function() {
var $ajaxcalls = [],
myArray = [];
// set up all the ajax calls that will populate my array
for(var i=0; i < 28; i++) {
$ajaxcalls[i] = $.ajax({
url : 'http://your.domain.com/blah',
data : i
}).success(function(m) {
myArray.push(m);
});
}
// this will setup the promise ---
// what will run when all 28 AJAX calls complete?
$.when.apply(null, $ajaxcalls).then(function() {
returnResults();
});
});
I've written about this some time back as well. I really think it's a nifty feature / concept that can be really powerful when used correctly. Javascript timers and schedules should work as well, but they can be unwieldy and may result in a bit of wait time before the actual completing logic fires.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With