Sveisvei
Sveisvei

Reputation: 762

Cant figure out how to return the callback function - need alternative solution

Im trying to return a callback value after the data is loaded, Im probably looking at this all wrong.

    var loadFromDatabase = function(callback){
  if (!obj.data.myarray) {
      // the problem is here, the jquery obj returns the ajax request obj
    return $.getJSON('http://validjson',function(data){
          obj.data.myarray = data.myarray;
          return callback();
        }); 
      } else {
    return callback();
  }
};
var findObjInArray = function(){
      // need i to be returned, but isnt working in the if statement, but works in the else statement
  return loadFromDatabase(function(){
    var l = obj.data.myarray.length;
    for (var i = 0; i < 50;i++) {
      if (i === 30) {
      return i;
        }
  }
    });
  };
  var myval = findObjInArray();
  console.log(myval);

Upvotes: 0

Views: 2626

Answers (4)

Quentin
Quentin

Reputation: 944020

Ajax is asynchronous (hence the name). You can't return anything from it.

The getJSON method causes an HTTP request to be sent. The function you pass is called on the event when that request is answered. It has no link to the calling function.

You have to write that function to do what you want to do with the data itself. You can't pass the data back and handle it in the calling function.

Upvotes: 2

jantimon
jantimon

Reputation: 38160

you have to use one more callback function:

var loadFromDatabase = function(callback){
        if (!obj.data.myarray) {
                    // the problem is here, the jquery obj returns the ajax request obj
                return $.getJSON('http://validjson',function(data){
                  return callback(data.myarray);
                    });

        } else {
                return callback();
        }

};


var findObjInArray = function( callback ){
      // need i to be returned, but isnt working in the if statement, but works in the else statement
  return loadFromDatabase(function( myarray ){


        var l = myarray.length;
        for (var i = 0; i < 50;i++) {
          if (i === 30) {
                 return callback ( i );
          }
        }
  });
};


findObjInArray(
   function ( myval )
   {
      console.log(myval);
   }
);

Upvotes: 0

kgiannakakis
kgiannakakis

Reputation: 104188

The problem is that the Ajax callback is called asynchronously. This means that the loadFromDatabase function returns first and then the callback is called. Therefore it is impossible to return from something from the callback.

You could use the async Ajax option to make the call asynchronous, but I don't recommend this. You need to revisit your architecture by taking into consideration the asynchronous nature of Ajax.

Upvotes: 0

reko_t
reko_t

Reputation: 56440

Should be just:

return callback;

Doing return callback() executes the callback function and returns its return value.

Upvotes: 2

Related Questions