【发布时间】: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