【问题标题】:How to get rejected promise from promise.all?如何从 promise.all 获得拒绝的承诺?
【发布时间】:2017-08-29 10:23:24
【问题描述】:

我已经编写了以下代码,用于在 Promise 的帮助下异步上传服务器上的文件。我们知道,一旦任何一个 Promise 失败,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;
  }

【问题讨论】:

标签: javascript reactjs ecmascript-6 es6-promise


【解决方案1】:

您可以将该信息添加到错误对象中:

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

【讨论】:

  • 这会给我第一个被拒绝的承诺。如果我想从 promise.all 获得所有被拒绝的承诺怎么办?在这种情况下,我们如何更改 promise.all?
  • 那么我们不能使用拒绝但必须Wait until all ES6 promises complete
  • 您能告诉我如何在我的示例中编写代码吗?
  • @HamidArrivy 和我回答中的代码很相似,只是不要throw而是return然后在then回调中区分错误和成功结果
  • 在promise.all的回调中?
猜你喜欢
  • 2016-07-08
  • 2017-06-19
  • 2018-07-23
  • 1970-01-01
  • 2019-11-25
  • 2019-04-19
  • 2017-09-04
  • 2017-03-31
相关资源
最近更新 更多