0

I'm trying to calculate a sum of results from an external API and I need to make a single request for each keyword I have. The code executes successfully but the function returns the value before all the ajax requests are completed. I tried to add "async" param but it's deprecated then I made this:

function calcTotal(arr) {
var t_docs = 0;
var i = 0;
var len = arr.length;
var aReq = []
for(i = 0; i < len; i++)
{
    console.log(i);
    var apiDataLQKT = {
        keyword: arr[i],
        start_date: "2015-01-01",
        end_date: "2015-06-01",
        format: 'jsonp',
        sources_types: sources,
        sources_names: names,
        domains: argDomains,
        words: terms,
        author_id: usrID,
        sentiment:sentiment,
        positive_threshold:posThresh,
        negative_threshold:negThresh,
        language:lang,
        author_location:geolocations,
        author_gender:genderID,
        typologies:typID,
        document_type:docType,
        source_base_url:'',
        emotion:'',
        metadata:'',
        order_sort:'',
        order_by:''
    }
    console.log(apiDataLQKT);
    aReq[i] = $.ajax({
        type:'GET',
        url:apiUrl+'LightQuantitativeKeywordTrend',
        contentType: 'application/javascript',
        crossDomain: true,
        dataType: 'jsonp',
        data: apiDataLQKT,
        success: function(json) {
            var res = json.LightQuantitativeKeywordTrend;
            t_docs += res.count;
            console.log("T_DOCS[" + arr[i] + "]: " + t_docs);
        }
    });
}
aReq[arr.length-1].done(function(data){
    return t_docs;
});
}

console log outputs:

Total: 0
T_DOCS[undefined]: 1445
T_DOCS[undefined]: 1521
...

What else can I try?

Avi
  • 141
  • 1
  • 1
  • 3
  • You're looking for promises. See [`$.when()`](https://api.jquery.com/jquery.when/) for an example of how to defer consuming the result set of an ajax call until the previously queued up calls have returned. It sounds like this is what you're asking. – War10ck Feb 26 '16 at 15:04

1 Answers1

0

You can not return a value from an asynchronous call, like an AJAX request, and expect it to work, because code waiting for the response has already executed by the time the response is received.

The solution to this problem is to run the necessary code inside the success: callback. ΩIn such case it is accessing data only when it is available.

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82