Javascript 回调 - 如何返回结果? [英] Javascript callback - how to return the result?

查看:19
本文介绍了Javascript 回调 - 如何返回结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力完全理解回调,我在最后的障碍中跌跌撞撞.

I am struggling to totally understand callbacks and i am stumbling at the final hurdle.

在 JS 中,我调用一个函数,然后使用 dojo rpc Json 服务调用 PHP 函数.我已经通过了 firebug 中的函数,PHP 正在执行并通过回调向我返回正确的响应,但我不知道如何将值返回到调用 JS 函数的初始 JS 变量?例如

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

            }
        }
    );
}

基本上我现在需要将 response.description 传递回函数一中的 var 测试变量.

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

感谢任何帮助

推荐答案

这是不可能的,因为回调是异步运行的.这意味着 getPhp 函数在回调执行之前返回(这是回调的定义,也是异步编程很难的原因之一;-)).

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 ;-) ).

您要做的是创建一个使用 test 变量的新方法.执行回调时需要调用该方法.

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.

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); });

最后一个方法创建了一个传递给 getPhp 函数的匿名函数".该函数在响应到达时执行.这样你就可以在数据到达后将数据传递给one(number)函数.

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.

这篇关于Javascript 回调 - 如何返回结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆