-2

I am using node js My code flow is as follows

function foo (){
//this returns a value
}
// function foo is an asynchronous call

since foo is an asynchronous method, i will not be able to access the return value like

var return_value = foo ();
console.log(return_value);

this would log as "undefined" in the console, since the asynchrnous call has not yet returned a value

so how should i get that value returned via an asynchronous call to be used in other areas of synchronous code flow?

thanks in advance :)

Maheedhar
  • 65
  • 1
  • 10

1 Answers1

4

The simplest solution is to use a callback:

function foo (callback) {
  callback(return_value);
}

foo(function (return_value) {
  console.log(return_value);
});

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95