Q:

Javascript callback - how to return the result?

I am struggling to totally understand callbacks and i am stumbling at the final hurdle.
Within JS I am calling a function which then calls a PHP function using a dojo rpc Json Service. I have stepped through the function in firebug and the PHP is executing and returning me the correct response via the callback but I don’t know how to return the value to the initial JS variable that invoked the JS function? E.g.
JS Function 1

Function one(){

Var test = getPhp(number);

}

function getPhp(number)
{

this.serviceBroker = new dojo.rpc.JsonService(baseUrl + '/index/json-rpc/');

    var result = serviceBroker.phpFunc(number);

    result.addCallback(
        function (response)
        {
            if (response.result == 'success')
            {
                return response.description;
               //I am trying to pass this value back to the 
               //var test value in   function one

            }
        }
    );
}

Basically i now need to pass response.description back to my var test variable in function one. 
Any help is appreciated

A:

This is not possible, since the callback is run asynchronously. This means that the getPhp function returns before the callback is executed (this is the definition of a callback, and one of the reasons asynchronous programming is hard ;-) ).
What you want to do is create a new method that uses the test variable. You need to call this method when the callback is executed.
i.e.
function one(result) {
  var test = result;
  // Do anything you like
}

function getPhp(number, callback) {
  this.serviceBroker = new dojo.rpc.JsonService(baseUrl + '/index/json-rpc/');
  result.addCallback(
    function (response)
    {
        if (response.result == 'success')
        {
           callback(response.description);
        }
    }
  );
}

getPhp(number, function(result) { one(result); });

This last method creates an 'anonymous function' that is passed to the getPhp function. This function gets executed at the time the response arrives. This way you can pass data to the one(number) function after the data arrives.

A:

The short answer is that you can't.
Do whatever you want to do with the data in the callback or functions you call from the callback. You can't return anything from it.

