【问题标题】:I need help in using double Promises in Javascript我需要帮助在 Javascript 中使用双重承诺
【发布时间】:2021-03-07 21:39:12
【问题描述】:

这是我尝试过的代码。

  // To get base64 code of file
  const toBase64 = file => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onloaded = () => resolve(reader.result.replace(/^data:.+;base64,/, ''));
    reader.onerror = error => reject(error);
  })

  // To make an array of files
  const getAttachments = async files => {
    let documents;
    try {
      documents = files.map(async file => {
        let base64 = await toBase64(file)
        return {
          doc: base64,
          documentName: file.name,
          documentType: file.type
        }
      })
    } catch {
      console.error('Failed to get files as base64')
    }
    return Promise.resolve(documents)
  }

我只是尝试通过使用上述 2 个函数来获取一个对象数组。 像下面这样;

getAttachments(Array.from(event.target.files)).then(documents => {
  console.info(documents)
}

但结果是

Logged out result in Console

我很想知道如何才能得到我想要的东西。 谢谢。

【问题讨论】:

  • documents = await Promise.all(files.map(async file =>
  • 感谢您的评论,但控制台中没有退出任何内容。
  • 你可能做错了......下面的答案怎么样?有效果吗?
  • 它也没有注销任何东西。
  • 嗨@Bravo,感谢您抽出宝贵时间。我可以看到问题所在。我已经在toBase64() 方法中将reader.onloaded 更改为reader.onload,它现在可以工作了。

标签: javascript arrays reactjs asynchronous promise


【解决方案1】:

尝试使用await 关键字返回一个已解决的promise 数组,而不是返回一个promise 数组。

试试这个

const getAttachments = async files => {
  let documents;
  try {
    documents = files.map(async file => {
      let base64 = await toBase64(file)
      return {
        doc: base64,
        documentName: file.name,
        documentType: file.type
      }
    })
    
    return await Promise.all(documents);
  } catch {
    console.error('Failed to get files as base64')
  }
}

【讨论】:

  • 感谢您的回答,但是当我运行此功能时,控制台中没有注销。 getAttachments(files).then(documents => { console.info(documents) }
  • 可能files 是空数组@baymax88 或者您可能被过滤掉了info 日志...尝试console.log 而不是console.info
  • 顺便说一句return await Promise.all(documents); ...就做return Promise.all(documents);
  • 我在let documents; 之前添加了console.log(files),它正在注销files,但结果尚未注销。
  • console.log(documents)return 输出@baymax88 之前做了什么
猜你喜欢
  • 2020-11-08
  • 1970-01-01
  • 2019-12-19
  • 1970-01-01
  • 2012-10-04
  • 2023-03-09
  • 1970-01-01
  • 2017-10-05
  • 1970-01-01
相关资源
最近更新 更多