Bjarne Hansen Bjarne Hansen - 2 months ago 10
Javascript Question

Getting data from multiple sources with promises

I'm trying to get the data from one or multiple sources, so I pass in an array of urls to get the data from and make a promise.

Then I try to use

Promise.all
in order to get all the data, but I don't get anything at all.

How can I solve this?

var getData = function (urls) {

var promises = [];
$.each(urls, function (index, url) {
var promise = new Promise(function (resolve, reject) {
$.ajax({
type: 'get',
url: url,
dataType: 'json',
success: function (data) {
console.log(data);
}
});
});

promises.push(promise);
});

console.log(promises);

Promise.all(promises).then(function () {
console.log('Complete');
});

};

Answer

You can do by using push response under array and use it on done()

var xhr_request=[];
var responses=[];
$.each(urls, function (index, url) {
    // you can push  any aysnc method handler
    xhr_request.push($.ajax({
        url: url,
        type:'get', 
        dataType:'json', 
        data:{user_name: users[i]},
        success: function(data){
            console.log('success of ajax response')
            responses.push(data);
        }
    }));
});


$.when.apply(null, xhr_request).done( function(){
    // all done
    console.log('all request completed')
    console.log(responses);
});

Here $.when provides a way to execute callback functions based on zero or more objects, usually Deferred objects that represent asynchronous events.

$.apply converts array elements as different arguments in function

$.done is call function after all async. request are completed.