我正在发出多个像这样的ajax请求
imgPromises = [];
imgPromise1 = $.ajax({
url: s3Url,
type: "POST",
data: s3FormData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false
}).done(function(data, status, formXHR) {
x = formXHR['responseText'].toString();
var uploadedUrl = x.match("<Location>(.*)</Location>")[1];
if ($(this).attr('id').startsWith('inp')) {
if ($(this).attr('id').startsWith('inp')) $('footer').css('background-image', 'url(' + uploadedUrl + ')');
footerBackground = $('footer').css('background');
}
}).fail(function() {
console.log("in ajax fail");
}.bind(this));
imgPromises.push(imgPromise1);
imgPromise2 = $.ajax({
url: s3Url,
type: "POST",
data: s3FormData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false
}).done(function(data, status, formXHR) {
x = formXHR['responseText'].toString();
var uploadedUrl = x.match("<Location>(.*)</Location>")[1];
if ($(this).attr('id').startsWith('inp')) {
if ($(this).attr('id').startsWith('inp')) $('footer').css('background-image', 'url(' + uploadedUrl + ')');
footerBackground = $('footer').css('background');
}
}).fail(function() {
console.log("in ajax fail");
}.bind(this));
imgPromises.push(imgPromise2);
Promise.all(imgPromises.then(function() {});
如果任何一个 Promise(imgPromise1
或 imgPromise2
)失败,则它不会转到 Promise.all
。
我希望在任何情况下它都应该转到 Promise.all
。
最佳答案
您在错误的地方使用了then
。
const Fail = function(error){this.error=error;};//special Fail type value
const isFail = o=>(o&&o.constructor)===Fail;//see if item passed is fail type
const isNotFail = o => !isFail(o);//see if item passed is not fail type
Promise.all(imgPromises
.map(
p=>Promise.resolve(p)/**convert to real promise*/
).map(
p=>p.catch(error=>new Fail(error))//single request failed, resolve with Fail value
)
)
.then(function (responses) {
// successes = responses.filter(isNotFail)
// failed = responses.filter(isFail)
})
.catch(function (err) {
//handle error
});
关于javascript - 如何使用 Promise 处理失败的 ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50800671/