执行promise.then之后在循环中多次调用该函数

时间:2018-09-28 15:44:49

标签: javascript jquery promise es6-promise

我进行了以下设置。对于每个表行,我从中提取一个字段,将其发送到另一个函数(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 :(得分:2)

您需要return中的jqXHRpostProfile()对象,并将它们也返回给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);
        }
    });
}
相关问题