0

When we print the value of index inside if it shows correct result but the same variable index when printed outside shows the value 0( value initially assigned). I think there is some problem with asynchronous behaviour of getJSON (not very sure). can somebody tell me what the possible solution is?

function get_build_id(query,node_file_name)
{
    //alert(query);
    flag = 0;
    index = 0;
    $.getJSON(node_file_name,function(data)
    {
            $.each(data,function(i,x)
            {
                index=index+1;
                if (x.name.toLowerCase()==query.toLowerCase() )
                {
                    flag=1;
                    //alert("index2 "+index);
                    return false;
                }
            });
    });
    //alert("index is "+ index);
    alert(flag);
    if(flag==1)
        return index;
    else
        return -1;
}

@Brad Christie

facing the same problem again. ind value gives the correct result but index value is always 0.

function get_build_id(query, node_fil_name, callback)
{
  var ind = 0;
  $.getJSON(node_fil_name, function(data)
  {
    $.each(data, function(i,x)
    {
      ind = ind + 1;
      if (x.name.toLowerCase() == query.toLowerCase()){
        callback(ind); // found match
        return false;
      }
    });
    callback(0); // no match found
  });
}

function get_hash_val(roomno,room_file_name,node_file)
{
        var flag=0,ind;
        get_build_id(roomno,node_file, function(ind)
        {
                alert(ind);
                index=ind;
        });
        alert(index);
        if(index!=0)
            return index;
        else
                return -1;
}

//get_hash_value is being called by another function to which index has to be returned

Pulkit Agarwal
  • 43
  • 1
  • 1
  • 7
  • Your line `alert(flag)` will be executed *before* the callback you passed to `.getJSON` because `.getJSON` is asynchronous. So of course `flag==0`, you haven't set it to anything else yet. – Matt Burland Nov 06 '13 at 15:57

2 Answers2

1

You nailed it; you're out of the work flow once you hit getJSON. You can't return a value with an AJAX call within a function, you'll need to pass it a callback method (which is then called on a successful AJAX query).

Picture something of the following:

function get_build_id(query, node_fil_name, callback){
  flag = 0;
  index = 0;
  $.getJSON(node_fil_name, function(data){
    $.each(data, function(i,x){
      index++; // index = index + 1;
      if (x.name.toLowerCase() == query.toLowerCase()){
        callback(index); // found match
        return false;
      }
    });
    callback(/* or return 0 */); // no match found
  });
}

Then implemented:

get_build_id('/some/file', 'foo', function(index){
  if (index !== undefined){ // or index != 0
    // match was found
  }
});

But Why?

AJAX is [essentially] executed on another thread. By the time the callback from getJSON is called, you're entire get_build_id block has been called and returned. So, index will never be another value other than the (expected) 0. if you need to rely on this value, you have to execute the code after the getJSOn callback has been called. And, to keep the workflow similar, you can forward on a callback to that method which is then called within the AJAX callback.

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
0

you definitely have a problem with async code. Since getJSON is async, the code setting the flag is going to be set after the parent function returns so it will always return -1

You can make sure of the inbuilt jQuery deferred/promise architecture to help alleviate the problem, but you may need to refactor your code to work in this case

can can just return the result of the getJSON call which is a jquery promise and pipe the return value

function get_build_id(query,node_file_name)
{
    var flag, index,
        promise = $.getJSON(node_file_name);

    return promise.then(function(data){

       &.each(data,function(i,x){
          index=index+1;

          if (x.name.toLowerCase()==query.toLowerCase() )
          {
            flag=1;
            return false;
          }
       });

      if(flag==1)
         return index;
      else
         return -1;
    })
}

get_build_id("foo", "bar").done(function(index){
  //do stuff here with the value
})
monastic-panic
  • 3,987
  • 1
  • 22
  • 20