繁体   English   中英

使用 await 和 async 处理承诺

[英]handling promises using await and async

我正在使用这个库进行文件上传。 这里说

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

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

但是我想通过 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.
});

我已经浏览了您正在使用的库的 .mv() 代码。 它确实有 promise 支持。

但是,它似乎 resolves() 带有空参数。

所以,如果你想使用异步等待,你可以使用,

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

你不能使用

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

它永远是未定义的,因为它不返回任何东西。

当没有提供回调时,库支持承诺,所以你应该能够等待它

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

要访问在中间件中创建的正确文件,您需要查看请求。 此外,function mv的响应不应返回任何内容。 只要它不抛出,你就可以使用 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