等待函数中的Ajax调用结束,然后将对象返回到外部变量 [英] Wait for Ajax call in function to end, THEN return object to an outside variable

查看:62
本文介绍了等待函数中的Ajax调用结束,然后将对象返回到外部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按照预期使用JavaScript异步。我想将收到的数据/对象分配给我需要的变量(DataModel01,DataModel02,DataModel03等)。我的想法是我对API数据的需求一直在变化,我只想定义一次获取数据的位置(API端点),以及存储它的局部变量/对象。

I want to use JavaScript asynchronous, as it was intended. I want to assign the recieved data/objects to as many variables as I'll need (DataModel01, DataModel02, DataModel03 and so on). The idea is that my need for API data change all the time, and I want to only have to define once where to get the data (API endpoint), and in what local variable/object to store it.

我正在这样做,它返回带有来自fetchDataJSON()函数的接收数据的对象。但是,如何让返回等待Ajax完成?我已经尝试了几件事,包括计时器和回调,但没有任何作用。

The way I'm doing it, it returns the object with recieved data from the fetchDataJSON() function. However, how do I make the return wait for the Ajax to finish? I've tried several things, including timers and callbacks, and nothing works at all.

我看到了关于ajax和async的其他问题,一般建议使用回调。所以我相信我可能会偏离轨道,但我需要一只手来找出一种方法来优雅地处理这个问题。我是否真的需要弄乱这样的计时器和丑陋的解决方案?

I saw the other questions regarding ajax and async, and generally it was suggested to use callbacks. So I believe I might be offtrack, but I need a hand to figure out a way to deal with this gracefully. Do I really need to mess with timers and ugly solutions like that?

function fetchDataJSON(endpointUrl) {
    var returnObj = [];

    // Ajax call
    $.ajax({
      type: "GET",
      url: endpointUrl,
      dataType: 'json',
      async: true,
      success: updateData,
      error: handleError
    });

    function updateData(data) {
        returnObj = data;
    }

    function handleError(XHR, message, error) {
        console.log("Failed XHR");
    }

    return returnObj; // Return JSON object
}

var DataModel01 = fetchDataJSON( "http://mydata.com/endpoint/sweetjson" );
var DataModel02 = fetchDataJSON( "http://mydata.com/endpoint/somethingelse" );






编辑:
我找到了工作解决方案现在,yihar。我已将Karman的答案标记为已接受,因为它是最接近解决方案的人。我的最终解决方案也受到了同事的启发,如下所示:


I found a working solution now, yihar. I've marked the answer by Karman as accepted, as it was the one closest to the solution. My final solution, which was also inspired by a coworker, is as follows:

var DataModel01 = [];
var DataModel02 = [];

function fetchDataJSON(endpointUrl, callbackWhenDone) {
    // Ajax call
    $.ajax({
      type: "GET",
      url: endpointUrl,
      dataType: 'json',
      async: true,
      success: updateData,
      error: handleError
    });

    function updateData(data) {
        callbackWhenDone(data);
    }

    function handleError(XHR, message, error) {
        console.log("Failed XHR");
    }
}

fetchDataJSON(
    "http://mydata.com/endpoint/sweetjson",
    function(newData) { DataModel01 = newData; }
);

fetchDataJSON(
    "http://mydata.com/endpoint/somethingelse",
    function(newData) { DataModel02 = newData; }
);


推荐答案

function fetchDataJSON(endpointUrl, callback) {
function updateData(data) {
    returnObj = data;

  callback(returnObj)
}

fetchDataJSON( "http://mydata.com/endpoint/sweetjson", getJson );

enter code here

function getJson(returnObj)
 {
    //do work with returnObj
  }

这篇关于等待函数中的Ajax调用结束,然后将对象返回到外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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