You cannot use the results of a function in other functions
P粉087951442
P粉087951442 2024-04-01 13:13:20
0
1
392

I have two functions

  1. convertToBase64(file) is used to convert files
  2. addData(values) is used to send the converted file. But the result of the second function is always undefined. how to solve this problem?
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,
  });
}

I tried try...catch and async-await functions, but I couldn't find a solution anyway

P粉087951442
P粉087951442

reply all(1)
P粉436052364

The

convertToBase64() function does not explicitly return an value, so the code you provide always returns undefined . You can change the function so that it returns a Promise once resolves " rel="nofollow noreferrer">FileReader Successfully read the file in base64 and handled any rejections or occurrences of mistake:

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);
  }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!