Evan Hessler
Evan Hessler

Reputation: 337

Execute promise.then after function called multiple times in a loop

I have the following set up. For each table row, I pull a field from it, send it to another function (buildProfile) which builds a new profile, which sends it to another function (postProfile) which posts the AJAX request. If there are 16 table rows to be saved, for example, usually only 9 of them get saved before the url redirect sends it to a new page. I would like to redirect to '/' only after all the promises are resolved. I've also taken out the URL redirect and they all successfully get saved.

$(document).on('click', '#save-button', function () {
    var promises = [];

    $('tr').each(function () {
        var field1 = $(this).children().eq(0).html();
        promises.push(buildProfile(field1));
    });

    Promise.all(promises).then(function () {
        window.location.replace('/');
    });
});


function buildProfile(field1) {
    var newProfile = {
       Field1: field1,
       Field2: 'foo',
       Field3: 'bar'
    }

    postProfile(newProfile, function () { });
}

function postProfile(profile, callback) {
    var url = '/api/profiles/';
    $.ajax({
        type: 'POST',
        url: url,
        contentType: 'application/json; charset=utf-8',
        dataType: "json",
        data: JSON.stringify(profile),
        success: function (result) {
            callback();
        },
        error: function (error) {
            console.log(error);
        }
    });
}

Upvotes: 0

Views: 51

Answers (1)

mehmetseckin
mehmetseckin

Reputation: 3107

You need to return the jqXHR objects in postProfile(), and return them to the caller in buildProfile() as well.

function buildProfile(field1) {
    var newProfile = {
       Field1: field1,
       Field2: 'foo',
       Field3: 'bar'
    }

    return postProfile(newProfile, function () { });
}

function postProfile(profile, callback) {
    var url = '/api/profiles/';
    return $.ajax({
        type: 'POST',
        url: url,
        contentType: 'application/json; charset=utf-8',
        dataType: "json",
        data: JSON.stringify(profile),
        success: function (result) {
            callback();
        },
        error: function (error) {
            console.log(error);
        }
    });
}

Upvotes: 2

Related Questions