如何等待异步函数的结果?
How to await the result from an async function?
我目前正在使用 Firebase 将图像上传到存储。
我创建了一个 uploadImage 函数,该函数获取图像并将其保存到 Firebase 存储,然后 returns 该保存图像的 url。当用户单击提交按钮时,我使用 uploadImage 函数保存该图像并取回 url。图像已正确保存,但正在记录的 url 未定义。我很确定这是我拥有的 aysnc-await 实现的问题。对此有什么想法吗?谢谢!
UploadForm.js:
import { uploadImage } from "../firebase/functions";
const UploadForm = () => {
const [image1, setImage1] = useState(null);
const saveForm = async (file) => {
const url1 = await uploadImage(image1);
console.log("URL", url1); //the url here is UNDEFINED
};
return (
<ImageUploadForm setImageProp={setImage1} />
<button
onClick={(e) => {
e.preventDefault();
saveForm(image1);
}}
></button>
);
上传图片函数:
const uploadImage = async (file) => {
const storageRef = storageService.ref().child("posts/" + file.name);
storageRef.put(file).on(
"state_changed",
(snapshot) => {},
(error) => {
console.log(error);
},
async () => {
return await storageRef.getDownloadURL();
}
);
};
你的 uploadImage
函数没有 return 任何东西,只是 return 承诺
return storageRef.put(file).on(
或者,(因为我不知道该函数是如何工作的/它是什么returns),可能
const uploadImage = (file) => {
return new Promise((resolve, reject) => {
const storageRef = storageService.ref().child("posts/" + file.name);
storageRef.put(file).on(
"state_changed",
(snapshot) => {},
(error) => {
console.log(error);
reject(error);
},
() => {
const res = storageRef.getDownloadURL();
resolve(res);
}
);
};
}
我目前正在使用 Firebase 将图像上传到存储。 我创建了一个 uploadImage 函数,该函数获取图像并将其保存到 Firebase 存储,然后 returns 该保存图像的 url。当用户单击提交按钮时,我使用 uploadImage 函数保存该图像并取回 url。图像已正确保存,但正在记录的 url 未定义。我很确定这是我拥有的 aysnc-await 实现的问题。对此有什么想法吗?谢谢!
UploadForm.js:
import { uploadImage } from "../firebase/functions";
const UploadForm = () => {
const [image1, setImage1] = useState(null);
const saveForm = async (file) => {
const url1 = await uploadImage(image1);
console.log("URL", url1); //the url here is UNDEFINED
};
return (
<ImageUploadForm setImageProp={setImage1} />
<button
onClick={(e) => {
e.preventDefault();
saveForm(image1);
}}
></button>
);
上传图片函数:
const uploadImage = async (file) => {
const storageRef = storageService.ref().child("posts/" + file.name);
storageRef.put(file).on(
"state_changed",
(snapshot) => {},
(error) => {
console.log(error);
},
async () => {
return await storageRef.getDownloadURL();
}
);
};
你的 uploadImage
函数没有 return 任何东西,只是 return 承诺
return storageRef.put(file).on(
或者,(因为我不知道该函数是如何工作的/它是什么returns),可能
const uploadImage = (file) => {
return new Promise((resolve, reject) => {
const storageRef = storageService.ref().child("posts/" + file.name);
storageRef.put(file).on(
"state_changed",
(snapshot) => {},
(error) => {
console.log(error);
reject(error);
},
() => {
const res = storageRef.getDownloadURL();
resolve(res);
}
);
};
}