My code:
var test = getData(email, password, data.sites);
console.log(test); // 4 sites, 4 responses
// TODO if 4 responses, call other function
function getData(email, password, sites) {
var formData = createFormDataArray(email, password, 0); // not so relevant
var returnValues = [];
sites.forEach(function (site) {
var url = 'http://' + site + '/test.php';
var newValue;
sendRequest(url, formData).done(function(value) {
newValue = value.status; // string
console.log(newValue);
});
returnValues.push(newValue); // add to array
});
console.log('------');
console.log(returnValues); // print array
return returnValues;
}
function sendRequest(url, formData) {
return $.ajax({
type: 'post',
url: url,
data: formData,
crossDomain: true,
dataType: 'json',
encode: true
});
}
What I want to do here is make multiple Ajax calls to different domains, put the results in an array.
If the array contains all the responses, I'd like to call another function, which I don't have right now.
The problem here is: the calls are asynchronous and I like to 'wait' until I receive all responses so that I can launch another function.
Currently is logged:
- Empty array
- Empty array
- newValue: "Ok"
What I need:
newValue: "Ok"
["Ok", "Ok", "Ok", "Ok"]
- ["Ok", "Ok", "Ok", "Ok"]
Or something like this. How can this be done?
**Edit: My solution: **
var defers = [];
sites.forEach(function (site) {
var url = 'http://' + site + '/test.php';
var defer = sendRequest(url, formData);
defers.push(defer);
});
$.when.apply(window, defers).always(function() {
// the other function
});
Create an array of 'defers'. Then, use the solution from the answer below.