Question

I'm working with multiple deferred Ajax calls and I would like to be dynamic about how I access their data. Rather than hardcoding in several parameters into the .then callback and using each individually, I would like to loop through the arguments object to access the data. This works fine, except I'm not able to determine from the json which data is from which Ajax call. I could solve this either by determining the url from the promise object (somehow) or figuring out which order the Ajax calls executed and assuming the data is in the same order.

Here's my code so far (mocked up for illustrating what I'm trying to do):

promises = [ 
    $.get("example.php", {}, function(){}),
    $.get("list.php", {}, function(){}),
    $.get("test.php", {}, function(){}),

]

$.when.apply(null, promises).then( function() {
     jsonarray = []
     $.each(arguments, function(index, value){
         // this is what I would like to work but doesn't
         // promises[index].success.url is how I imagine accessing 
         //"list.php" or "test.php"
         if (jsonarray[promises[index].success.url] == null){
              jsonarray[promises[index].success.url] = []
         }
         jsonarray[promises[index].success.url] = value
         doSomethingWith(jsonarray)
     })

Is there another way to match each argument with the Ajax call that produced it? What I don't want to do is this:

$.when.apply(null, promises).then( function(examplejson, listjson, testjson) {
         // this is lame
         exampledoSomethingWith(examplejson)
         listdoSomethingWith(listjson)
         testdoSomethingWith(testjson)
})

Thanks! Sara

Was it helpful?

Solution

http://jsfiddle.net/6EZsh/2/

$(function() {

    var objs = [{'one':1},{'two':2},{'three':3}];
    var urls = [];

    ajaxCall = function(i) {
        return $.ajax({
            url:'/echo/html/',
            method: 'POST',
            data: {id:i}
        }).done(function () {
            urls.push({obj:i,url:this.url});
        });   
    }

   $.when.apply($,
        objs.map(function(i) {
            return ajaxCall(i);
        })
    ).then(
        console.log(urls)
    );

});

As mentioned the object you receive in your "then" are the success handlers for all your deferreds. So the only real way to pair this information would be in the success handler of your Ajax calls. Example above.

OTHER TIPS

let's try

var urls = [
    "example.php",
    "list.php",
    "test.php"
];
var promises = [  
];

var jsonarray = {};
$.each(urls, function(index, value) {
    promises[index] = $.get(urls[index], {}, function(){});
    promises[index].success(function(data) {
        jsonarray[urls[index]] = data; //is this the value you want in the jsonarray??
    });
});

$.when.apply(null, promises).then( function() {
    doSomethingWith(jsonarray) 
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top