piscript
piscript

Reputation: 419

How to Return value from a callback function

I'm having a function declaration as below. How do i return a value from within a function/anonymous function to the parent.

Here is the code, that I'm trying to work on

LB.getData = function(key) {
    if(!key) return;

    appAPI.db.async.get(key, function(value){
        data = (value === null) ? null : JSON.parse(value);
        return data
    });
};


var myData = LB.getData('user');

Upvotes: 2

Views: 969

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

Looks like an asynchronous function. The whole point of asynchronous programming is that you do not return values. You subscribe to callbacks which is where you consume the results. Because if you return values, that means that the caller of your function will have to wait until this value is available. And waiting is bad, because you would be freezing this caller.

So one possibility is to provide your parent function with a callback parameter that would allow the consumer of this function to get the results of the asynchronous operation:

LB.getData = function(key, callback) {
    if(!key) return;

    appAPI.db.async.get(key, function(value) {
        var data = (value === null) ? null : JSON.parse(value);
        // invoke the callback and pass the results to it
        callback(data);
    });
};

and then simply provide a callback function when consuming the parent:

LB.getData('user', function(data) {
    // use the data here
    alert(data.someProperty);
});

Upvotes: 7

Related Questions