当等待多个ajax调用的函数时jquery

时间:2022-05-01 12:18:04

I have a javascript function which waits for multiple ajax calls and then combines the responses into a single javascript array. I then need to return the array (data) from the function but don't know how I can do it.

我有一个javascript函数,它等待多个ajax调用,然后将响应组合到一个javascript数组中。然后我需要从函数返回数组(数据),但不知道我该怎么做。

Can I have some help on this please.

请问我可以帮忙吗?

var myCombinedArray = fetchData();

function fetchData() {
    var data = [];
    $.when(fetchThisYearsData(),fetchLastYearsData()).done(function(dataThisYear, dataLastYear){
        data[0] = dataThisYear[0];
        data[1] = dataLastYear[0];
        console.log(data);
    }); 
    return data;
}

I have read enough to know that myCombinedArray will be empty because the ajax is asynchronous but I don't know what to do to achive my desired result.

我已经阅读了足够的知道myCombinedArray将是空的,因为ajax是异步的,但我不知道如何实现我想要的结果。

thanks


Update

I've tried to implement the callback but am a bit lost. I am getting an error "callback is not a function".

我试图实现回调,但有点迷失。我收到一个错误“回调不是一个函数”。

$(function () {
  var myCombinedArray;
  fetchData(function (myCombinedArray) {
        //what to do here?
    });

  console.log(myCombinedArray);
})

function fetchData(callback) {

    $.when(fetchThisYearsData(), fetchLastYearsData()).done(function(dataThisYear, dataLastYear){
        var data = [];
        data.push(dataThisYear[0]);
        data.push(dataLastYear[0]);
        callback(data);
    }); 
}

1 个解决方案

#1


2  

You can use a callback function which will be called once all the data is populated

您可以使用回调函数,该函数将在填充所有数据后调用

fetchData(function (myCombinedArray) {
    //do your stuff
});

function fetchData(callback) {
    $.when(fetchThisYearsData(), fetchLastYearsData()).done(function (dataThisYear, dataLastYear) {
        var data = [];
        data.push(dataThisYear[0]);
        data.push(dataLastYear[0]);
        console.log(data);
        callback(data);
    });
}

Read More

#1


2  

You can use a callback function which will be called once all the data is populated

您可以使用回调函数,该函数将在填充所有数据后调用

fetchData(function (myCombinedArray) {
    //do your stuff
});

function fetchData(callback) {
    $.when(fetchThisYearsData(), fetchLastYearsData()).done(function (dataThisYear, dataLastYear) {
        var data = [];
        data.push(dataThisYear[0]);
        data.push(dataLastYear[0]);
        console.log(data);
        callback(data);
    });
}

Read More