【问题标题】:React.js cant log data from outside foreach - Event/promisesReact.js 无法记录来自外部 foreach 的数据 - 事件/承诺
【发布时间】:2023-02-20 22:33:56
【问题描述】:
我只是想从 firestorage 获取下载 url 并将其推送到空数组。
在 handleSubmit 中,我尝试了这个,但它记录了空数组。如果我在里面尝试它,它会正确记录
let images = [];
thumbnail.forEach(async (file) => {
const uploadPath = `property/${user.uid}/${file.name}`;
const imgRef = ref(storage, uploadPath);
await uploadBytes(imgRef, file);
images.push(await getDownloadURL(imgRef));
console.log(images); //Logs correct array of urls
});
console.log(images);// Logs empty array
【问题讨论】:
标签:
javascript
reactjs
firebase
google-cloud-firestore
【解决方案1】:
您的回调是异步的。 console.log 在回调完成之前触发。
要在记录之前等待所有异步回调完成,请使用 Promise.all() 和 map 返回承诺并等待它们。
let images = [];
Promise.all(thumbnail.map(async (file) => {
const uploadPath = `property/${user.uid}/${file.name}`;
const imgRef = ref(storage, uploadPath);
await uploadBytes(imgRef, file);
images.push(await getDownloadURL(imgRef));
console.log(images);
}).then(() => {
console.log(images);
});
您可以通过从回调返回并删除临时图像数组来进一步改进
Promise.all(thumbnail.map(async (file) => {
const uploadPath = `property/${user.uid}/${file.name}`;
const imgRef = ref(storage, uploadPath);
await uploadBytes(imgRef, file);
return await getDownloadURL(imgRef);
}).then((images) => {
console.log(images);
});