1

I have seen lots of posts on stackoverflow regarding getting the returned value of an asynchronous call in a callback function but I would like to know if I could get the result without going much inside the callback.

For Eg: Current Scenario:

myFunc(arg1,arg2, mycallback);
..
function mycallback(values)
{
//Process values
alert(values);
}

What I would like to have:

var returnedValues = myFunc(arg1,arg2, function mycallback(values)
{
return values;
});

// Now I would to use the returnedValues here...

Is the above scenario possible? Kindly let me know.

Cheers.

Neophile
  • 5,660
  • 14
  • 61
  • 107

2 Answers2

0

You cannot do that, what you could do is make use of Promises

Quote: ...I could get the result without going much inside the callback.

If you are concerned about the callback hell, that is something you can mitigate by using promises:

Example from bluebird library:

You should use promises to turn this:

fs.readFile("file.json", function(err, val) {
    if( err ) {
        console.error("unable to read file");
    }
    else {
        try {
            val = JSON.parse(val);
            console.log(val.success);
        }
        catch( e ) {
            console.error("invalid json in file");
        }
    }
});

Into this:

    fs.readFileAsync("file.json").then(JSON.parse).then(function(val) {
        console.log(val.success);
    })
    .catch(SyntaxError, function(e) {
        console.error("invalid json in file");
    })
    .catch(function(e) {
        console.error("unable to read file")
    });
Daniel Conde Marin
  • 7,588
  • 4
  • 35
  • 44
0

You can use a promise library. Here is implementation using jQuery promise

(function ($) {
    function myFunc(arg1,arg2){
          var defer = $.Deferred(),
              result=arg1+arg2; 
          defer.resolve(result);
          return defer.promise();
    }

    myFunc(1,2).then(function(result){
        console.log('result is: '+result)
        //manipulate result as you want
        result=result+1;
        showFinalResult(result);
    });
    function showFinalResult(result){
        alert(result);
    }
})(jQuery);

http://jsfiddle.net/gfmvgc8p/