Heim > Fragen und Antworten > Hauptteil
Ich habe zwei Funktionen
async function convertToBase64(file) { const fileReader = new FileReader(); fileReader.onload = () => { const srcData = fileReader.result; console.log('scrData: ', srcData); // result is correct return srcData; }; fileReader.readAsDataURL(file); } async function addData(values) { const converted = await convertToBase64(values.file); console.log(converted); // result undefined await addDoc(collection(db, 'list'), { image: converted, }); }
Ich habe die Funktionen try...catch und async-await ausprobiert, konnte aber trotzdem keine Lösung finden
P粉4360523642024-04-02 11:48:48
convertToBase64()
函数不会显式返回值,因此您提供的代码始终返回 undefined
。您可以更改该函数,使其返回一个Promise,一旦FileReader 已成功读取 base64 中的文件,并处理任何 reject
ions 或发生的错误:
const imgFileInput = document.getElementById("img"); imgFileInput.addEventListener("change", addData); function convertToBase64(file) { return new Promise((resolve) => { const fileReader = new FileReader(); fileReader.onload = () => { const srcData = fileReader.result; resolve(srcData); }; fileReader.onerror = (error) => { reject(error); }; fileReader.readAsDataURL(file); }); } async function addData() { try { const imgFile = imgFileInput.files[0]; const converted = await convertToBase64(imgFile); console.log(converted); } catch (error) { console.error("Error while converting to Base64:", error); } }