armin
armin

Reputation: 306

handling promises using await and async

I am using this library for file uploading. Here it says

 sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) {
    if (err)
      return res.status(500).send(err);

    res.send('File uploaded!');
  });

But I want to use this using await and async so when I try like

router.put("/upload", async(req,res)=>{
    const isUploaded = await sampleFile.mv('/somewhere/on/your/server/filename.jpg');
    console.log(isUploaded) // it gives me undefined over here.
});

Upvotes: 0

Views: 204

Answers (2)

Edward Romero
Edward Romero

Reputation: 3106

Library supports promises when no callback is provided so you should be able to just await it

Resource: https://github.com/richardgirges/express-fileupload/blob/1216f4f0685caca7f1ece47f52c6119dc956b07d/lib/fileFactory.js#L62

To access the proper file create in middleware you need to look at the request. Also the response of the function mv is not supposed to return anything. As long as it doesn't throw then you're good to go.

    app.post("/upload", async (req, res) => {
      if (!req.files || Object.keys(req.files).length === 0) {
        return res.status(400).send("No files were uploaded.");
      }

      // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
      let { sampleFile } = req.files;

      // Use the mv() method to place the file somewhere on your server
      try {
        await sampleFile.mv("/somewhere/on/your/server/filename.jpg");
        res.send("File uploaded!");
      } catch (e) {
        res.sendStatus(500);
      }
    });

Upvotes: 1

Rupjyoti
Rupjyoti

Reputation: 399

I have gone through the code of .mv() of the library that you are using. It does have promise support.

However, it seems like it resolves() with empty argument.

So, if you want to use async await, you can use,

router.put("/upload", async(req,res)=>{
    try{
         await sampleFile.mv('/somewhere/on/your/server/filename.jpg');
         res.send('File uploaded!');
    } catch(err){
         res.status(500).send(err);
});

You cannot use

const isUploaded = await mvPromise('/somewhere/on/your/server/filename.jpg');

It will always be undefined because it does not return anything.

Upvotes: 1

Related Questions