我有两个不同的ajax post方法,它们都在一个循环上运行(每个方法在下一个开始之前完成),在我使用async之前:false并且一切正常,但它现在已经折旧并抛出错误。是否有另一种方法,以便我可以在循环中同步运行方法?我已经尝试将每个函数包装在自己的函数中并使用.done()进行调用,但这会使我的帖子保持在循环中。
function postLoop() {
len = 3
backorderPayLoad = []
cancelPayLoad = []
for (var i = 0; i < len; i++) {
backorder = {
"quantity": 20,
"note": "Backorder",
}
cancel = {
"quantity": 20,
"note": "Cancel",
}
backorderPayLoad.push(backorder);
cancelPayLoad.push(cancel);
$.ajax({
url: myurl,
method: 'POST',
contentType: : "application/json",
async: false,
data: JSON.stringify(backorderPayLoad[i]),
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
})
$.ajax({
url: myurl2,
method: 'POST',
contentType: : "application/json",
async: false,
data: JSON.stringify(cancelPayLoad[i]),
beforeSend: function(xhr, settings)
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
})
}
}
答案 0 :(得分:0)
基于将数组传递给postloop()
来构建递归承诺链的示例。
let orders =[{..},{...},{...}];
// initiialize
postloop(orders).then(finalData => {
// do something with final data after all requests completed
console.log('Final', finalData);
}).catch(err=>{ // use `fail()` if jQuery version < 3
console.log('oops something wrong in at least one request');
});
function postloop(orders) {
let finalData = [],
orderIndex = 0;
function completeRequests(res) {
// push results of each set of requests to array
finalData.push(res);
orderIndex++;
if (orderIndex < orders.length) {
// return another set of request promises to add to chain
return doRequests(orders[orderIndex]).then(completeRequests)
} else {
// and finally return array of data to resolve all promises
return finalData;
}
}
// return promise chain
return doRequests(orders[orderIndex]).then(completeRequests);
}
// function will be called recursively in postloop() always returning promise
function doRequests(order) {
let backorder = $.extend({}, order);
backorder.note = "Backorder";
// return request promises
return firstRequest().then(secondRequest)
function firstRequest() {
return $.ajax({
url: '/echo/json/',
method: 'POST',
data: {
json: JSON.stringify(backorder)
}
}).then(backorderResponse => {
console.log('First request complete for id: ', backorder.id)
return backorderResponse;
});
}
function secondRequest(backorderResponse) {
let cancel = {
id: backorderResponse.id, // do something with data from first response,
qty: backorderResponse.qty,
note: 'Cancel'
};
return $.ajax({
url: '/echo/json/',
method: 'POST',
data: {
json: JSON.stringify(cancel)
}
}).then(cancelOrderResponse => {
// do something with each of the 2 responses
let combinedData = {
cancel: cancelOrderResponse,
backorder: backorderResponse
};
console.log('Second request complete for id: ', cancel.id)
return combinedData;
});
}
}
的 DEMO 强>