Dhayalan Pro
Dhayalan Pro

Reputation: 589

Javascript : The global variables value cannot be changed

FB.api(...,function (..){
  var a = 0 ;
  FB.api(...,function (l){
         a = l.data.length;
  });
     alert(a) ;     
});

the value of a displayed is zero !? Shouldn't it be Giving a value l.data.length ?! If i have alert(a) ; after the line a = l .data.length ; its working :/

UPDATE :

since FB.api is asynchronous is there any any other way to modify a ?

Upvotes: 0

Views: 446

Answers (4)

user3140466
user3140466

Reputation:

FB api is asynchronous. so you should alert the value of a at your callback function

function (l){
     a = l.data.length;
     alert(a);
})

Upvotes: 1

WebServer
WebServer

Reputation: 1396

its asynchronous; so by the time

function (l){
     a = l.data.length;
})

executes alert(a) would already have been executed.

EDIT: next operation we should write after the variable a has been set in the same function

function (l){
     a = l.data.length;
     nextThing1();
     nextThing2()
})

Upvotes: 0

griffon vulture
griffon vulture

Reputation: 6774

FB api is asynchronous.

If you need to use variable after changing its value, send a callback to the function and get the variable in the callback.

var callback = function(){
  alert(a);
}
FB.api(...,function (l, callback){
         a = l.data.length;
         callback();
  });

Upvotes: 1

Shin
Shin

Reputation: 189

a = l.data.length is in the callback function, it will be executed when the callback function is called.

But alert(a) will be executed immediately after the FB.api.

Upvotes: 0

Related Questions