我有以下代码:
const imgURL = () => {
const fileName = report.reporter.avatar.Pc.path.segments[8];
const storageRef = storage.ref('images');
storageRef.child(`/${fileName}`).getDownloadURL().then((url) => {
console.log(url) // here I am getting the url in the console
return url;
});
}
console.log(imgURL()); // here its undefiend
对于某些我不知道为什么我无法获得函数返回的结果
答案 0 :(得分:1)
您可以使用async
/ await
尝试类似的操作,但我不知道async
/ await
是否可以起到反应作用。
const imgURL = async () => {
const fileName = report.reporter.avatar.Pc.path.segments[8];
const storageRef = storage.ref('images');
const url = await storageRef.child(`/${fileName}`).getDownloadURL().catch((error) => { throw error });;
return url;
}
更改您的调用方法:
console.log(await imgURL());
答案 1 :(得分:0)
修复我的代码(useState)的原因
const [avatarUrl, setAvatarUrl] = useState('');
const imgURL = async () => {
const fileName = report.reporter.avatar.Pc.path.segments[8];
const storageRef = storage.ref('images');
await storageRef.child(`/${fileName}`).getDownloadURL().then((url) => {
setAvatarUrl(url);
});
}
imgURL();