简体   繁体   English

将异步/等待与 firebase 一起使用

[英]using async/await with firebase

I'm trying to use async/await to get images from firebase storage, and this is my function:我正在尝试使用异步/等待从 firebase 存储中获取图像,这是我的 function:

import { ref as sRef, getDownloadURL } from "firebase/storage";
...    
async getCharacterIconUrl(character) {
  return await getDownloadURL(sRef(storage, `characters/${character}/icon`));
}

And then, I use this function here:然后,我在这里使用这个 function:

import { ref, child, get } from "firebase/database";
...
async componentDidMount() {
  const dbRef = ref(db);

  let snapshot = await get(child(dbRef, "en/characters"));
  if (snapshot.exists()) {
    let characters = Object.keys(snapshot.val()).map((key) => {
      return {
        _id: key,
        img: this.getCharacterIconUrl(key),
        ...snapshot.val()[key],
      };
    });
    this.setState({ characters: characters });
  } else {
    console.log("No data available");
  }
}

The problem I have is that img inside characters is never resolved.我遇到的问题是img inside characters从未解决。

How can I solve this?我该如何解决这个问题?

Your getCharacterIconUrl function is async so you need to await it.您的getCharacterIconUrl function 是async的,因此您需要等待它。

Try this...尝试这个...

const characters = await Promise.all(
  Object.entries(snapshot.val()).map(async ([_id, val]) => ({
    _id,
    img: await this.getCharacterIconUrl(_id),
    ...val,
  }))
)
this.setState({ characters });

Note that the .map() callback is also async .请注意, .map()回调也是async的。 I'm also using Object.entries() since you want both keys and values.我还使用Object.entries()因为您需要键和值。

Since getCharacterIconUrl is an async function, it returns a promise. Therefore, your img field is a promise;由于getCharacterIconUrl是一个异步 function,它返回一个 promise。因此,您的img字段是一个 promise; combined with map() , that becomes like an array of promise. Therefore, we can use Promise.all() to resolve them结合map() ,就变成了一个 promise 的数组。因此,我们可以使用Promise.all()来解析它们

async componentDidMount() {
  const dbRef = ref(db);

  let snapshot = await get(child(dbRef, "en/characters"));
  if (snapshot.exists()) {
    let characterPromises = Object.keys(snapshot.val()).map(async (key) => {
      return {
        _id: key,
        img: await this.getCharacterIconUrl(key),
        ...snapshot.val()[key],
      };
    });
    this.setState({ characters: await Promise.all(characterPromises)});
  } else {
    console.log("No data available");
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM