1

Please have a look at this method. In this function response I am calling two functions findConnectedUsersRelationship() and displayUsers(response.users).

The problem is displayUsers(response.users) method runs and gets result before findConnectedUsersRelationship(). My requirement is I need to run first findConnectedUsersRelationship() and second displayUsers(response.users). Second method depends on first method.

function filterUsers(location, gender, youngAge, oldAge, interests){
        var userId = signedUserId;
        $.post(urlHolder.filter, {
            userId: userId,
            location: location,
            gender: gender,
            youngAge: youngAge,
            oldAge: oldAge,
            interests: interests
        }, function(response) {
            console.log('User response <<>>', response.users.length);
            var filteredUsers;
            findConnectedUsersRelationship();
            displayUsers(response.users);

        });
    }



// To find connected user relationship
var relationshipList = new Array;
function findConnectedUsersRelationship() {
    try {
        $.post(urlHolder.findConnectedUsersRelationship, {
            userId : signedUserId
        }, function(response) {
            //console.log('response downforanything: ', JSON.stringify(response));
            if (response) {
                for (var counter = 0; counter < response.users.length; counter++) {
                    relationshipList.push(response.users[counter].id);
                }
            } else {
                console.log('No connected users >>>> ');
            }
            //console.log('relationshipList.length',relationshipList);
            console.log('relationshipList length in auto complete *** ',relationshipList.length);
        });
    } catch (e) {
        console.log('findConnectedUsersRelationship Exception >>>', e);
    }

}
Kumaresan Perumal
  • 131
  • 1
  • 1
  • 13

1 Answers1

5

$.post returns a promise.

You can use this to continue your code:

function filterUsers(location, gender, youngAge, oldAge, interests){
    $.post(url, { ... }, function(response) {
        findConnectedUsersRelationship().done(function() {
            displayUsers(response.users); 
        });
    });
}

and change your findConnectedUsersRelationship() to return the promise from its ajax function,so instead of:

function findConnectedUsersRelationship() {
    $.post(...

it becomes

function findConnectedUsersRelationship() {
    return $.post(...
freedomn-m
  • 27,664
  • 8
  • 35
  • 57