In the code below I'm loading two ajax requests.
The first is 'getTeams()' which loads an array of teams, each with an id. For each team, I then use the id to get all users that match the id within 'getUsers(teamId)', and set that to teams[i].users
However, the setting of teams[i].users does not wait for a response, and continues with the for loop. It then console logs the 'teams' array created. And only then does it load the ajax requests.
Is there a way to wait for the request to complete within 'getUsers()' before teams[i].users is set?
Thanks
function getUsers(teamId) {
$.ajax({
type: 'GET',
dataType: "json",
url: 'https://app.gohire.io/' + gohire.client.id + '/api/get-users/?teamId=' + teamId + '/',
success: function(response) {
return response;
},
error: function(data) { alert((data.responseJSON) ? ((data.responseJSON.error) ? data.responseJSON.error : 'An error occurred') : 'An error occurred'); }
});
return false;
}
function getTeams() {
$.ajax({
type: 'GET',
dataType: "json",
url: 'https://app.gohire.io/' + gohire.client.id + '/api/get-teams/',
success: function(response) {
teams = response;
for (var i = 0; i < teams.length; i++) {
var team = teams[i];
teams[i].users = getUsers(teams[i].id);
}
console.log(teams);
render();
},
error: function(data) { alert((data.responseJSON) ? ((data.responseJSON.error) ? data.responseJSON.error : 'An error occurred') : 'An error occurred'); }
});
}
getTeams();
UPDATE: This is the only solution that I found to the problem. Although the question has been marked as a duplicate of this question, I did not find me answer there, as the main problem (for me) was caused by the for loop.
However, it did help me find the actual answer to my problem which can be viewed here
$.ajax({
type: 'GET',
dataType: "json",
url: 'https://app.gohire.io/' + gohire.client.id + '/api/get-teams/',
success: function(response) {
teams = response;
var ajaxCount = 0;
// the below ajax request won't be called until later
// therefore, 'i' must be captured, which is done by creating a new scope
// creating a new scope in javascript is done by creating a new function
for (i = 0; i < teams.length; i++) {
(function(i) {
$.ajax({
type: "GET",
dataType: "json",
url: 'https://app.gohire.io/' + gohire.client.id + '/api/get-users/?teamId=' + teams[i].id + '/',
success: function(request) {
teams[i].users = request || [];
// count ajax requests, to only render on last
ajaxCount++;
if (ajaxCount == teams.length) { render(); }
}
});
})(i);
}
},
error: function(data) { alert((data.responseJSON) ? ((data.responseJSON.error) ? data.responseJSON.error : 'An error occurred') : 'An error occurred'); }
});