【问题标题】:Return variable from object从对象返回变量
【发布时间】:2015-12-21 00:07:06
【问题描述】:

我需要从这段代码中返回结果变量,我正在尝试大约一个小时,但仍然没有成功...你能帮帮我吗?我也研究过物体,但没有成功......

api.prototype.ajax = function()
{
    marmottajax({
                            url: "http://localhost:8080/bp/stranka/api/test",
                            method: "post",
                            parameters: 
                            {
                                image: 8,
                                by: "click"
                            }
                        }).then(function(result) 
                        {
                            result; //this variable i want to get/return to my function
                        });
}

【问题讨论】:

    标签: ajax variables object return


    【解决方案1】:

    您不能通过 AJAX 调用 return - 您需要使用承诺或回调。这是一个带有回调的示例:

    api.prototype.ajax = function(callback) {
        marmottajax({
            url: "http://localhost:8080/bp/stranka/api/test",
            method: "post",
            parameters: {
                image: 8,
                by: "click"
            }
        }).then(function(result) {
            callback(result); //this variable i want to get/return to my function
        });
    }
    

    并使用它:

    api.ajax(function(data) {
        console.log(data);
    });
    

    【讨论】:

    • 它没有解决我的问题,因为我需要这个变量作为我的函数的输出,使用我的 API 的客户端不想使用这个......可能有同步 ajax,但我没有试试它如何与画布游戏一起工作,也许游戏会冻结:/
    • @Raiper34 -- 同步 ajax 将导致 UI 完全锁定 - 如果可以接受,请使用它。否则,您将无法将此函数的结果分配给变量。
    【解决方案2】:

    我刚刚了解了 Promise :P,也许我能帮上忙。因为我看到你在用then,不知道你用的是不是Promise。如果你用的是Promise,在函数里面应该有两个参数resolvedrejected,你可以通过resolved函数传递你的返回值.

    这是一个可以帮助你的例子! source url

    var promise = new Promise(
    function(resolve, reject) {
      console.log('in Promise constructor function');
      setTimeout(function() {
        console.log('in setTimeout callback');
        if (Math.random() > 0.5){
          resolve('Here is your data');
        } else {
          reject('Something happend, it causes error');
        } 
      }, 100);
    });
    console.log('created promise');
    promise.then(
      function(result) {
        console.log('promise returned: ' + result);
      },
      function(err){
        console.log(err);
      }
    );
    console.log('hooked promise.then()');
    

    【讨论】:

    • 它没有解决我的问题,因为我需要这个变量作为我的函数的输出,使用我的 API 的客户端不想使用这个......可能有同步 ajax,但我没有试试它如何与画布游戏一起工作,也许游戏会冻结:/
    猜你喜欢
    • 2014-09-15
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多