简体   繁体   English

使用 await 和 async 处理承诺

[英]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但是我想通过 await 和 async 来使用它,所以当我尝试时

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

I have gone through the code of.mv() of the library that you are using.我已经浏览了您正在使用的库的 .mv() 代码。 It does have promise support.它确实有 promise 支持。

However, it seems like it resolves() with empty argument.但是,它似乎 resolves() 带有空参数。

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.它永远是未定义的,因为它不返回任何东西。

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资源: 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.此外,function mv的响应不应返回任何内容。 As long as it doesn't throw then you're good to go.只要它不抛出,你就可以使用 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);
      }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM