我已经编写了以下代码,用于在promises的帮助下异步上传服务器上的文件。我们知道,一旦任何承诺失败,promise.all将会失败。所以,我想知道哪个承诺实际上失败了,在我的情况下,知道承诺失败的文件名。我正在尝试console.log(e1),但它没有向我提供有关失败承诺的信息。有人可以帮我做吗?
uploadFilesAndSendStatus(stateType, notes, estimate, visibleToCustomer = null)
{
let filesPromise = Promise.resolve([]);
const promises = this.state.files_to_upload.map((file) => {
return this.uploadFilesOnServer(file);
});
filesPromise = Promise.all(promises).then((results) => {
return [].concat(...results);
}).catch((e1) =>{
console.log(e1);
this.setState({
serverActionPending: false,
serverActionComplete: false,
file_upload_try_again: true,
});
});
}
UploadFilesOnServer代码是:
uploadFilesOnServer(file) {
let files=[];
let file_id='';
const image=file;
const promise = getAttachmentUploadURL(this.props.task.id)
.then((imageUrlResponse) => {
const data = new FormData();
data.append('file-0', image);
const { upload_url } = JSON.parse(imageUrlResponse);
return uploadAttachment(upload_url, data);
})
.then ((updateImageResponse) => {
file_id= JSON.parse(updateImageResponse);
files.push(file_id);
return files;
});
return promise;
}
答案 0 :(得分:3)
您可以将该信息添加到错误对象中:
const promises = this.state.files_to_upload.map((file, i) => {
return this.uploadFilesOnServer(file).catch(err => {
const e = new Error("upload failed");
e.index = i;
e.filename = file
throw e;
});
});
const filesPromise = Promise.all(promises).then(res => [].concat(...res)).catch(e1 => {
console.log(e1);
…
});