Home > Enterprise >  How to further process a filename of a formidable form with asnc functions
How to further process a filename of a formidable form with asnc functions

Time:09-27

I am having trouble processing the name of a file I upload to my server. I use formidable to parse a form and save the data to my database. I then want to return the filename the id I get from my database to the client.

My api route (without error handling etc) calls uploadFile() when it receives a POST request

export default async function handler(req, res) {
      await uploadFile(req, res);
      break;
}

In uploadFile I process the form and send the response back to the client without the insertId everything works. But I can´t figure out how to wait for my db response or where to call it.

export async function uploadFile(req, res) {
    const form = new IncomingForm({
      multiple: false,
    });

    await form.parse(req).on("file", (name, file) => {

      // This wont work since I cant await inside the await call
      const insertId = await writeToDb("INSERT into [...]")

      res.status(200).json({filename: file.originalFilename, id:insertId })
    });
}

It feels like I am missing a general concept about async programming here. Any help that leads me in the right direction is greatly appreciated!

CodePudding user response:

You can use await if you make the handler function async:

form.parse(req).on("file", async (name, file) => {
  //                       ^^^^^
  const insertId = await writeToDb("INSERT into [...]")
  res.status(200).json({filename: file.originalFilename, id:insertId })
});

There are some caveats:

  • this only works if your uploads consist of only one file (but I assume they do, because you send back a response after processing the first file)
  • uploadFile will return before the response it sent back; judging by the implementation of handler(), that won't be an issue in this situation though.
  • Related