Home > Back-end >  await only valid in async function meanwhile i already put "async" in the function [duplic
await only valid in async function meanwhile i already put "async" in the function [duplic

Time:09-22

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) {}
}
};

CodePudding user response:

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

  • Related