foxenn_pro
foxenn_pro

Reputation: 71

Callback and return with Node.js

I am stuck with a problem here, where I want to keep my functions separately (in files) for a neater code.

In my Route.js, I am calling a function like this:

app.post('/pay', function(req, res){
    User.getPaypal(function(output){ 
        console.log(output) //i am not getting this result(output)
    })
})

The function is exported in another file as below:

module.exports.getPaypal = function(){
    var create_payment_json= {
        //some values
    };

    paypal.payment.create(create_payment_json, function (err, payment) {
        if (err) {
            return err;
        } else {
             return payment;
        }
    });
}

I want to get a return value of payment or err as a return for the called function in the route.

How can I make this work?

Upvotes: 0

Views: 55

Answers (2)

Yogesh
Yogesh

Reputation: 4784

You should start with understanding concept of callback which is based on concept of closure

As for your problem you were missing the use of passed callback function. It should be as below

module.exports.getPaypal = function(callback){ //callback argument was missing
    var create_payment_json= {
        //some values
    };

    paypal.payment.create(create_payment_json, function (err, payment) {
        if (err) {
            callback(undefined, err); // callback function being invoked
        } else {
            callback(payment, undefined); // would be better if you have two arguments to callback first for result second for error
        }
    });
}

Upvotes: 2

slebetman
slebetman

Reputation: 113876

Let's step back and consider the basics of how functions work.

Let's assume you wrote the function:

function double () {
    var x = 1;
    return x * 2;
}

Then you call it as

var y = double(100);

and you see that y is 2 instead of 200?

What would you say is wrong with this?

If you said you've declared double to not take an argument, you'd be right. The fix is:

function double (x) {
    return x * 2;
}

Now let's look at your function:

var getPaypal = function () {
    /** for now it does not matter what's here **/
}

Now you are calling the function as:

function mycallback (output) {
    console.log(output);
}

getPaypal(mycallback);

I hope you see what's wrong. It's obvious that you've declared the function as:

function getPaypal() {}

when what you want is:

function getPaypal(anotherFunction) {}

Now, how do you pass the result to the callback function? Easy, just call it:

function getPaypal(anotherFunction) {
    /** some processing **/

    anotherFunction(result); // this is how you pass the result to the callback
}

A callback is no different than a number or string or array. It's just something passed to your function.

Upvotes: 3

Related Questions