Javascript callback - how to return the result?

后端 未结 3 834
别跟我提以往
别跟我提以往 2020-12-10 17:55

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 doj

相关标签:
3条回答
  • 2020-12-10 18:35

    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.

    0 讨论(0)
  • 2020-12-10 18:36

    A much cleaner answer:

    getPhp(number);
    
    function one(data){
        var test = data;
        // do what you want
    }
    
    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')
                {
                    one(response.description);
                }
            }
        );
    }
    
    0 讨论(0)
  • 2020-12-10 18:38

    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.

    0 讨论(0)
提交回复
热议问题