2017-08-29 237 views
2

我已经写了下面的代码,用于在承诺的帮助下异步上传服务器上的文件。而且我们知道promise.all将失败,一旦任何承诺失败。所以,我想知道哪个承诺实际上失败了,在我的案例中,承诺失败的文件名称。我正在尝试console.log(e1),但它没有给我关于失败的承诺的信息。任何人都可以帮我做吗?如何从promise.all获得拒绝承诺?

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

会是一个解决方案:http://bluebirdjs.com/docs/ api/reflect.html – frulo

+0

我不认为你想'JSON.parse'的'e1' – Bergi

+0

是的。编辑。 @Bergi 但我仍然无法获得所需的信息。 – HamidArrivy

回答

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); 
    … 
}); 
+0

这会给我第一个被拒绝的承诺。如果我想从promise.all获得所有被拒绝的承诺怎么办?我们该如何改变promise.all在这种情况下? – HamidArrivy

+0

然后我们不能使用拒绝,但必须[等到所有ES6承诺完成](https://stackoverflow.com/questions/31424561/wait-until-all-es6-promises-complete-even-rejected-promises) – Bergi

+0

你能告诉我如何在我的例子中编码吗? – HamidArrivy