0

So i make a facebook query ( fql ) in a function, and i need to use the returned results in another function, but the query takes some time. How can i delay the second function until the whole query loaded?

Stefan Perju
  • 288
  • 6
  • 21

2 Answers2

2

You can do so by passing callback function to FB.api:

FB.api('/fql', {q: 'YOUR QUERY HERE'}, function(response) {
  console.log(response);
});

BTW, you probably may want to read next couple of questions to get more familiar with how closures and asynchronous execution works in JavaScript.

Community
  • 1
  • 1
Juicy Scripter
  • 25,778
  • 6
  • 72
  • 93
0

Here is an example I found here:

FB.api(
  {
    method: 'fql.query',
    query: 'SELECT name FROM user WHERE uid=me()'
  },
  function(response) {
    // !!! here you should write second function !!!
    amotherFunction(response);
    alert('Your name is ' + response[0].name);
  }
);

function(response){} will fire after query has completed

Community
  • 1
  • 1
karaxuna
  • 26,752
  • 13
  • 82
  • 117
  • In some queries it takes longer to take the response, and if i return the response, and call it in a function, the second function will load before the query ( because the query takes longer). – Stefan Perju May 01 '13 at 08:51
  • @StefanPerju, you cannot just return the result from closure function you need to pass it other way. – Juicy Scripter May 01 '13 at 08:56
  • @Juicy Scripter Or, i could call the function i need, in this one. But only after the query finished loading. More precisely, i need to put the retrieved info in a json, and then call a function with this json as parameter. – Stefan Perju May 01 '13 at 09:01