【问题标题】:Execute promise.then after function called multiple times in a loop在循环中多次调用函数后执行 promise.then
【发布时间】:2018-09-28 23:49:04
【问题描述】:

我有以下设置。对于每个表行,我从中提取一个字段,将其发送到另一个函数(buildProfile),该函数构建一个新的配置文件,然后将其发送到另一个发布 AJAX 请求的函数(postProfile)。例如,如果要保存 16 个表行,通常只有其中 9 个被保存,然后 url 重定向将其发送到新页面。我想仅在 all 解决承诺后重定向到“/”。我还取出了 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);
        }
    });
}

【问题讨论】:

  • 你没有从你的函数中返回承诺,你需要return $.ajax(return postProfile。你的 promises 数组目前不包含任何 promises。
  • @Liam 就是这样。谢谢!

标签: javascript jquery promise es6-promise


【解决方案1】:

您需要returnpostProfile() 中的jqXHR 对象,并将它们也返回给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);
        }
    });
}

【讨论】:

    猜你喜欢
    • 2021-06-07
    • 1970-01-01
    • 2023-03-19
    • 2020-02-13
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    相关资源
    最近更新 更多