-2

I have to call functionA from functionB

function A() {
  // File read etc functionality goes here//
  return data;
}

function B() {
  var result = A(); 
}

Here due to asynchronous my result var is empty even function A returns data.Can anyone please help me.Thanks.

tester
  • 1
  • 1
  • if the asynchronous code is `// File read etc functionality goes here//` then, yes, you can't return result of asynchronous code synchronously – Jaromanda X Sep 09 '17 at 08:51
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jonas Wilms Sep 09 '17 at 08:59

1 Answers1

0

Your example is incorrect. There is no asyncroniusly in provided code. And to call function A inside B you don't need to write function again, just write A(), and you will get your result. To get async result you should change your coding approach.

If you wan't some result that will be async, you should consider use promises or callbacks.

Like here:

//cb will be callback function that is provded by the caller code
//in this example it is a anonymouse function from B
function A(cb) {
  // File read etc functionality goes here//
  //this callback should be called when data is ready
  cb(data);
}

function B() {
  A(function (data) {
    //do with data what you want here
  });
}
Artsiom Miksiuk
  • 3,896
  • 9
  • 33
  • 49