Javascript 在循环中多次调用函数后执行promise.then
我有以下设置。对于每一个表行,我从中提取一个字段,将其发送到另一个函数(buildProfile),该函数构建一个新的概要文件,并将其发送到另一个函数(postProfile),该函数发布AJAX请求。例如,如果要保存16个表行,通常在url重定向将其发送到新页面之前,只保存其中的9个。只有在所有承诺都解决后,我才想重定向到“/”。我还执行了URL重定向,它们都成功保存Javascript 在循环中多次调用函数后执行promise.then,javascript,jquery,promise,es6-promise,Javascript,Jquery,Promise,Es6 Promise,我有以下设置。对于每一个表行,我从中提取一个字段,将其发送到另一个函数(buildProfile),该函数构建一个新的概要文件,并将其发送到另一个函数(postProfile),该函数发布AJAX请求。例如,如果要保存16个表行,通常在url重定向将其发送到新页面之前,只保存其中的9个。只有在所有承诺都解决后,我才想重定向到“/”。我还执行了URL重定向,它们都成功保存 $(document).on('click', '#save-button', function () { var p
$(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);
}
});
}
您需要
返回postProfile()
中的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);
}
});
}
您需要返回postProfile()
中的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);
}
});
}
如果不从函数返回承诺,则需要return$.ajax(
以及return postProfile
)。您的承诺数组目前不包含任何承诺。@利亚姆就是这样。谢谢!如果不从函数返回承诺,则需要return$.ajax(
和返回postProfile
。您的承诺数组目前不包含任何承诺。@利亚姆:就是这样。谢谢!