Выполнить обещание .hen после функции, вызванной многократно в цикле - PullRequest
0 голосов
/ 28 сентября 2018

У меня есть следующие настройки.Для каждой строки таблицы я извлекаю из нее поле, отправляю его в другую функцию (buildProfile), которая создает новый профиль, который отправляет его в другую функцию (postProfile), которая отправляет запрос AJAX.Например, если нужно сохранить 16 строк таблицы, обычно только 9 из них сохраняются до того, как перенаправление URL отправит их на новую страницу.Я хотел бы перенаправить на '/' только после все обещания будут выполнены.Я также убрал перенаправление URL, и все они успешно сохраняются.

$(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);
        }
    });
}

1 Ответ

0 голосов
/ 28 сентября 2018

Вам необходимо return jqXHR объекты в postProfile() и вернуть их вызывающей стороне также в buildProfile().

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);
        }
    });
}
...