将async/await与firebase一起使用



我正在尝试使用async/await从firebase存储中获取图像,这是我的功能:

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

然后,我在这里使用这个函数:

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

我遇到的问题是characters内部的img永远无法解决。

我该如何解决这个问题?

您的getCharacterIconUrl函数是async,因此您需要等待它。

试试这个。。。

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

请注意,.map()回调也是async。我也在使用Object.entries(),因为您需要键和值。

由于getCharacterIconUrl是一个异步函数,它返回一个promise。因此,您的img字段是一个承诺;再加上map(),这就像一个承诺的数组。因此,我们可以使用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");
}
}

最新更新