0
function squre(val) {
    main.add(val,function(result){
        console.log("squre = " + result); //returns 100 (2nd line of output)
        return result;
    });
}

console.log(squre(10));  // returns null (1st line of output)

I need 100 as output in both of the lines.

Ebenezar John Paul
  • 1,570
  • 5
  • 20
  • 41
Devang Bhagdev
  • 633
  • 2
  • 8
  • 14

2 Answers2

0

You can't, as you have the asynchronous function main.add() that will be executed outside of the current tick of the event loop (see this article for more information). The value of the squre(10) function call is undefined, since this function doesn't return anything synchronously. See this snippet of code:

function squre(val) {
    main.add(val,function(result){
        console.log("squre = " + result);
        return result;
    });

    return true; // Here is the value really returned by 'squre'
}

console.log(source(10)) // will output 'true'

and The Art of Node for more information on callbacks.

To get back data from an asynchronous function, you'll need to give it a callback:

function squre(val, callback) {
  main.add(val, function(res) {
    // do something
    callback(null, res) // send back data to the original callback, reporting no error
}

source(10, function (res) { // define the callback here
  console.log(res);
});
Paul Mougel
  • 16,728
  • 6
  • 57
  • 64
0

It rather depends on the nature of main.add(). But, by its use of a callback, it's most likely asynchronous. If that's the case, then return simply won't work well as "asynchronous" means that the code doesn't wait for result to be available.

You should give a read through "How to return the response from an AJAX call?." Though it uses Ajax as an example, it includes a very thorough explanation of asynchronous programming and available options of control flow.

You'll need to define squre() to accept a callback of its own and adjust the calling code to supply one:

function squre(val, callback) {
    main.add(val, function (result) {
        console.log("squre = " + result);
        callback(result);
    });
});

squre(10, function (result) {
    console.log(result);
});

Though, on the chance that main.add() is actually synchronous, you'll want to move the return statement. They can only apply to the function they're directly within, which would be the anonymous function rather than spure().

function squre(val) {
    var answer;
    main.add(val, function (result) {
        console.log("squre = " + result);
        answer = result;
    });
    return answer;
}
Community
  • 1
  • 1
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199