views:

1128

answers:

2

Hi there, two functions need to be executed in Javascript, the second one only after the first has finished.

The first populates an array with getJSON, and the second will then manipulate it.

However, getJSON is asynchronous, thus it will not pause the order of execution to make the program work properly so that the array finishes loading before the second function can execute. How can one use Jquery's ajaxComplete() or else the getJSON callback to simply run the second function once the data has finished loading via getJSON.

Thanks.


here is the code:

function fetch_ids(user) 
var url = 'http://test.com/ids/' + escape(user) + '.json?callback=?';
// populate array ids[] with JSON data --uid[] array declared globally
$.getJSON(url, function(data) {
for( var i = 0; i < data.length; i++ ) ids[i] = data[i];
});
// test array and run alert
for(i=0;i<uid.length;i++){
for(j=0;j<ids.length;j++){
if(uid[i]==ids[j])
{alert('matched: ' + uid[i]);}
}
}
// finish test
}
+4  A: 

Wouldn´t this work?

$.getJSON(url, params, function (jsonData){
  // populate array
  // call 2nd function.
});

Worst case, if you have your 2 funcions already defined elsewhere:

$.getJSON(url, params, function (jsonData){
  firstFunction(jsonData);
  secondFunction(jsonData);
});
Seb
No that doesn't work unfortunately. It's about triggering a second function once the $.getJSON has finished execution.
Adrian33
I don´t get it... what´s wrong with triggering the 2nd call as the last line of the getJSON callback? Why do you need to wait for the callback to finish?
Seb
If you need to populate the array, do it in the first call or inside the getJSON callback; after that, you don´t need to wait for it to finish; you can call the 2nd function right there. If not, then please update your question specifying why is that.
Seb
Indeed, this is the answer to your question.
thenduks
the sample code is above. the testing section won't execute as everyone thinks. maybe it's just me, so far it hasn't worked.
Adrian33
If I split the two functions up, and execute in another separate function it works, but I have to execute the program twice, giving the first function time to load up the array.
Adrian33
Well, the problem is you should insert the second for inside the getJSON callback, at the end of it. That way it will run only after you populate the array. We all misunderstood your question because you said you had 2 functions, but actually you had none; code was all around.
Seb
A: 

Check this similar post... How to initiate another jQuery .ajax call based on the result from an initial .ajax call?

The trick is to put the second call in the success function of the first call.

kevink
Well, this is similar to what I said above... but I still don´t get why he didn´t like my answer :(
Seb