sansSpoon
sansSpoon

Reputation: 2185

Adding additional property to $.ajax() callback with promise

I need to make 2 calls to an API which each contain some of the total data, that then needs to be iterated over. Call 1 gets two jsonp objects:

[{
    "id": 17,
    "name": "A",
    "campaign_code": "CAP20481"
},{
    "id": 18,
    "name": "B",
    "campaign_code": "CAP20481"
}]

Call 2 uses the ID from the first call to get an integer. I then need the corresponding "name" and integer. So far I have:

function getStoreCounts() {
    var campaignID = $("input[title='Campaign ID']").val();
    var storeLists = $.ajax({
        type: "GET",
        dataType: "jsonp",
        url: "/apiIndex?callback=?&campaign_code=" + campaignID.toString(),
    }),
    storeCount = storeLists.then(function(data) {       
        $.each(data,function(i,storeList){
            $.extend(storeList,{stores:''});
            var getCount = $.ajax({
                type: "GET",
                dataType: "jsonp",
                url: "/apiStoreCount?callback=?&list_id=" + storeList.id.toString(),
            });

            getCount.done(function(count) {
                storeList.stores = count;
            });

        });
        return data;
    });

    storeCount.done(function(data) {
        console.log(data);
        $.each(data,function(i,tierCount){
            console.log("Tier: "+tierCount.name);
            console.log("Stores: "+tierCount.stores);
        });
    });
}

At the final done promise return when I log out the whole data array, I get the stores values for each object intact. But when I try to iterate over each object in the array I'm missing the stores value. Attached output from Chrome.

enter image description here

Upvotes: 1

Views: 282

Answers (1)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

You need to wait for all inner promises to resolve. $.when

storeCount = storeLists.then(function(data) {
    // array of promises       
    var counting = $.map(data,function(storeList){
        $.extend(storeList,{stores:''});
        var getCount = $.ajax({
            type: "GET",
            dataType: "jsonp",
            url: "/apiStoreCount?callback=?&list_id=" + storeList.id.toString(),
        });

        return getCount.then(function(count) {
            storeList.stores = count;
        });

    });
    // wait for all 
    return $.when.apply($, counting).then(function() {
       return data; //return modified data
    })
});

And a side note on naming convetion. Your function was named getStoreCounts but returns undefined. Let it return the final promise.

function gettingStoreCounts() {
    var campaignID = $("input[title='Campaign ID']").val();
    var storeLists = $.ajax({...}),
    return storeLists.then(...);
}

And use the result on call side

gettingStoreCounts().then(/*log, whatever*/)

Upvotes: 2

Related Questions