0

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'); }
});
Community
  • 1
  • 1
James Moran
  • 624
  • 1
  • 7
  • 14
  • See the linked question's answers. Your `getUsers` function never returns anything (the `return response` inside the `success` callback returns that value from the callback [which doesn't do anything], not from `getUsers`), and *can't* return the result of an asynchronous operation in any case. – T.J. Crowder Dec 28 '16 at 12:24
  • Thank you very much for this. I did search around but have not seen this answer – James Moran Dec 28 '16 at 12:25
  • Assign team users in the success callback of `getUsers()` – Anupam Dec 28 '16 at 12:25
  • 1
    use promise instead will help you – anshuVersatile Dec 28 '16 at 12:27
  • @T.J.Crowder. I went through the link you provided, however, I did not find the answer to my question there. I have updated my code with the solution that worked for me. Thank you for the help though! – James Moran Dec 28 '16 at 21:49
  • @JamesMoran: That **is** the solution, in the accepted answer to the linked question. – T.J. Crowder Dec 29 '16 at 08:13

1 Answers1

-1
function getUsers(teamId, fun) {
    $.ajax({
        type: 'GET',
        dataType: "json",
        url: 'https://app.gohire.io/' + gohire.client.id + '/api/get-users/?teamId=' + teamId + '/',
        success: fun,
        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];
                getUsers(teams[i].id,function(teams[i].users){
                    //do the stuff here
                });
            }

            console.log(teams);
            render();
        },
        error: function(data) { alert((data.responseJSON) ? ((data.responseJSON.error) ? data.responseJSON.error : 'An error occurred') : 'An error occurred'); }
    });
}
getTeams();
anshuVersatile
  • 2,030
  • 1
  • 11
  • 18