Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to wait until Array is filled (asynchronous)

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!

like image 692
Weedjo Avatar asked Nov 25 '11 10:11

Weedjo


People also ask

How do you wait for loop to finish?

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.

Is array push async?

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.

How do I return an array from async function?

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.


2 Answers

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.

like image 144
lfxgroove Avatar answered Oct 23 '22 17:10

lfxgroove


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.

like image 30
Richard Neil Ilagan Avatar answered Oct 23 '22 18:10

Richard Neil Ilagan