0

It says that await only valid for async function but i already put the async word before the (req,res,next) , did i code it wrong?

const axios = require("axios");
const FormData = require("form-data");
const imageKit = async (req, res, next) => {
if (req.files) {
  try {
    const files = req.files;
    const values = Object.values(files);
    values.map((perArray) => {
      perArray.forEach((item) => {
        if (item.mimetype === "image/jpeg" || item.mimetype === "image/png") {
          const newForm = FormData();
          const encodedFile = item.buffer.toString("base64");
          newForm.append("file", encodedFile);
          newForm.append("fileName", item.originalname);
          const encodedKey = Buffer.from(
            process.env.IMAGE_KIT + ":"
          ).toString("base64");
          const result = await axios({
            method: "POST",
            url: "https://upload.imagekit.io/api/v1/files/upload",
            data: newForm,
            headers: {
              ...newForm.getHeaders(),
              Authorization: `Basic ${encodedKey}`,
            },
          });
        }
      });
    });
  } catch (error) {}
}
};
  • dont use map unless you want to mutate the values in the array, imo should rewrite so you abstract out the code which does the upload to imagekit, i.e in a method called upload, then make it async, that would then also remove all the libs like axios, form-data etc and leave the middleware clean, import your helper script then use a bog-standard `for` loop to loop over the files to upload – Lawrence Cherone Sep 22 '21 at 11:54

1 Answers1

2

Your function that you pass to forEach is not async and it is not recommended to use async in forEach.

Using async/await with a forEach loop

Ivan V.
  • 7,593
  • 2
  • 36
  • 53