【问题标题】:Promise is still been returned after await when converting image to base64 string将图像转换为base64字符串时,等待后仍然返回承诺
【发布时间】:2020-05-13 16:38:41
【问题描述】:

我有下面的方法将图像转换为base64字符串

  const toBase64 = file => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });

然后我决定像下面这样使用这个功能:

    let base_strings = files.map(async file => {
      let image = await toBase64(file);
      console.dir(image); //this console base string
      return image;
    });

但是当我尝试访问我的 base_string 数组时,我仍然得到如下承诺:

我不确定我做错了什么,我需要能够在数组中获取我的 base64 字符串。

【问题讨论】:

  • async 在函数前面是语法糖,用于“将函数结果包装成一个承诺并返回它”。所以你需要await你数组的所有成员。 (我的反应不够好,无法给出完整的答案。)

标签: javascript reactjs async-await


【解决方案1】:

尝试像这样使用Promise.all():

let base_strings = files.map(file => {
  return toBase64(file);
});

const myImages = await Promise.all(base_strings);

【讨论】:

  • 太棒了!请考虑通过单击箭头图标下方左侧的勾号图标来接受我的回答。 @AbelAgoi
【解决方案2】:

map 函数返回一个数组,你需要像这样使用 Promise.all

await Promise.all(files.map())

【讨论】:

  • 谢谢你,它也可以,但我会选择@user9408899 的答案。你太棒了。
【解决方案3】:

async await 不能与 forEach 或 map 一起使用:

let base_strings = files.map(async file => {
    let image = await toBase64(file);
    console.dir(image); //this console base string
    return image;
});

您可以使用simple for loop 做到这一点,但这应该在async 函数中,如下所示:

const getFiles = async (files) => {
    const base_strings = [];
    for(let i=0;i<files.length; i++) {
        let image = await toBase64(file);
        console.dir(image); //this console base string
        base_strings.push(image);
    }
    return base_strings;
}

【讨论】:

  • 嗯,今天才知道。太好了!
  • @AbelAgoi,如果你需要同步行为,你应该这样做,promise.all将所有请求一起发出而不是一个一个
  • @AbelAgoi,如果对你有帮助,也请点赞
猜你喜欢
  • 2017-10-17
  • 2017-02-03
  • 1970-01-01
  • 1970-01-01
  • 2018-09-07
  • 2014-07-21
  • 2018-12-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多