node.jsasync-awaitformidable

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


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!


Solution

  • 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: