我编写了以下代码,用于在 Promise 的帮助下在服务器上异步上传文件。我们知道,一旦任何一个 promise 失败,promise.all 就会失败。所以,我想知道哪个 promise 实际上失败了,在我的例子中, promise 失败的文件名。我正在尝试 console.log(e1) 但它没有给我有关失败 promise 的信息。有人可以帮我做吗?
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;
}
最佳答案
您可以将该信息添加到错误对象中:
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);
…
});
关于javascript - 如何从 Promise.all 获取被拒绝的 Promise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45936640/