0

I need some concept of threading java script.Actually I struck in one problem .Problem is that I have one function A () calling function B and C.

function A(){
   B();
   C();
}

function B(){
   //doing some task 
   i=something;
   alert(i);
}

function C(){
   // i need value I here.
   alert(i)    //getting undefined 
}

I need to synchronised call ...

Shawn31313
  • 5,978
  • 4
  • 38
  • 80
user2563256
  • 187
  • 1
  • 5
  • 14
  • Define `i` as a global variable. – Shawn31313 Jul 17 '13 at 04:51
  • 2
    All those calls are synchronized. In other words, the call to `B()` will be called and completed, before the call to `C()`. So I'm not sure why you're talking about [Threading](http://en.wikipedia.org/wiki/Thread_(computing)), when it looks like you're talking about [Scope](http://en.wikipedia.org/wiki/Scope_(computer_science)). – Erik Philips Jul 17 '13 at 05:04
  • please check this question http://stackoverflow.com/questions/17689556/how-to-synchronise-call-in-jquery-or-javascript – user2563256 Jul 17 '13 at 05:12

3 Answers3

5

How about

function A(){
   C(B());
}

function B(){
   //doing some task 
   var i=something;
   return i;
}

function C(i){
   // i need value I here.
   alert(i)    
}

or split out for readability

function A(){
   var resultFromB = B(); //
   C(resultFromB);
}

function B(){
   //doing some task 
   var result=something;
   return result; // return it to calling function
}

function C(resultOriginallyFromB) { // passing it
   alert(resultOriginallyFromB);    
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

Set i as global like,

var i=null;// global i
function A(){
   B();
   C();
}

function B(){
   //doing some task 
   i=something;
   alert(i);
}

function C(){
   i need value I here.
   alert(i)    //getting undefined 
}

Read this also

Alternatively, you can use return in B() like,

function A(){
   i=B();
   C(i);//passing i in C()
}

function B(){
   //doing some task 
   i=something;
   alert(i);
   return i;//return i
}

function C(i){
   // value i has been passed in.
   alert(i);
}
Community
  • 1
  • 1
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

Actually it should not really be alerting undefined in function C. As i would have become globally defined already, without the use of var.

Besides try doing it this way, so that you don't clutter the global space:

(function() {

  var i;

  function A(){
   B();
   C();
  }

  function B(){
     //doing some task 
     i=4;       // --- or something
     alert(i);  // --- will alert 4
  }

  function C(){
     // i need value I here.
     alert(i)    // --- will alert 4
  }

  A();  // --- Assuming you were calling 'A' earlier as well

})();  

And yes, nothing related to threading here.

loxxy
  • 12,990
  • 2
  • 25
  • 56