gpt4 book ai didi

javascript - 将可下载的 URL 上传到 Firestore。 await on .map throw 'await' 对此表达式的类型没有影响

转载 作者:行者123 更新时间:2023-12-05 05:40:06 31 4
gpt4 key购买 nike

我使用 React Hook Form 构建了一个表单。

用户可以上传姓名、地址、图片等。我的问题是上传图片

在表单提交上 -> 首先,我想将图像上传到 Firebase 存储。之后,我想获取那些可下载的 URL 数组并将它们存储在我的 Firestore 列表中。

我可以成功上传到 Firebase 存储。 问题是用 url 设置 imageUrls 状态。例如,如果我上传了 2 个文件,它返回 [undefined, undefined]

由于组件正在缩小,我决定将 uploadImages 功能分开。但是我面临一些异步问题。

上传文件函数

import {
getStorage,
ref,
uploadBytesResumable,
getDownloadURL,
} from 'firebase/storage';

const uploadImages = (file, fileName) => {
const storage = getStorage();
const storageRef = ref(storage, `images/${fileName}`);

const uploadTask = uploadBytesResumable(storageRef, file);

// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on(
'state_changed',
(snapshot) => {
// Observe state change events such as progress, pause, and resume
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case 'paused':
console.log('Upload is paused');
break;
case 'running':
console.log('Upload is running');
break;
}
},
(error) => {
// Handle unsuccessful uploads
},
() => {
// Handle successful uploads on complete
// For instance, get the download URL: https://firebasestorage.googleapis.com/...
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
console.log('File available at', downloadURL);
return downloadURL;
});
}
);
};

export default uploadImages;

这是 onSubmit 事件处理程序

  const onSubmit = async (formData) => {
setLoading(true);
try {
if (geolocationEnabled) {
const response = await fetch(
`https://maps.googleapis.com/maps/api/geocode/json?address=${formData.location}&key=${process.env.REACT_APP_GEOCODE_API_KEY}`
);
const data = await response.json();

if (data.status === 'ZERO_RESULTS') {
setValue('location', undefined);
} else {
setValue('location', data.results[0]?.formatted_address);
}

const lat = data.results[0]?.geometry.location.lat ?? 0;
const lng = data.results[0]?.geometry.location.lng ?? 0;

setValue('geolocation', { lat, lng });
} else {
setValue('geolocation', {
lat: formData.latitude,
lng: formData.longitute,
});
}

// uploading images
if (formData.imageUrls.length > 0) {
const imageURLs = Array.from(formData.imageUrls).map((file) =>
uploadImages(file, `${formData.userRef}-${file.name}`)
);
setValue('imageUrls', imageURLs);
}

await addDoc(collection(db, 'listings'), formData);
toast.success('Listing created successfully!');
} catch (error) {
console.log(error);
toast.error(getErrorMessageForToastify(error.code));
}
setLoading(false);
};

当我写作时

      if (formData.imageUrls.length > 0) {
const imageURLs = Array.from(formData.imageUrls).map((file) =>
{
const url = await uploadImages(file, `${formData.userRef}-${file.name}`)
return url
}
);
setValue('imageUrls', imageURLs);
}

我收到警告“等待”对此表达式的类型没有影响。因为它不返回 promise 。我该如何解决这个问题?

谢谢

最佳答案

我通过在 uploadImages 函数中返回 Promise 找到了解决方案。


const uploadImages = async (file, fileName) => {
return new Promise((resolve, reject) => {
const storage = getStorage();
const storageRef = ref(storage, `images/${fileName}`);

const uploadTask = uploadBytesResumable(storageRef, file);

// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on(
'state_changed',
(snapshot) => {
// Observe state change events such as progress, pause, and resume
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
const progress =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case 'paused':
console.log('Upload is paused');
break;
case 'running':
console.log('Upload is running');
break;
}
},
(error) => {
// Handle unsuccessful uploads
reject(error);
},
() => {
// Handle successful uploads on complete
// For instance, get the download URL: https://firebasestorage.googleapis.com/...
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
console.log('File available at', downloadURL);
resolve(downloadURL);
});
}
);
});
};

这是修改后的


// uploading images
if (formData.images.length > 0) {
setIsFileUploading(true);
const imgUrls = await Promise.all(
[...formData.images].map((file) =>
uploadImages(
file,
`${formData.userRef}-${file.name}-${Math.random()}`
)
)
).catch(() => {
toast.error("Image couldn't uploaded");
return;
});

if (imgUrls && imgUrls.length > 0) {
setValue('imageUrls', imgUrls);
}
setIsFileUploading(false);
}

关于javascript - 将可下载的 URL 上传到 Firestore。 await on .map throw 'await' 对此表达式的类型没有影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72481950/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com