繁体   English   中英

在运行下一个 .then - node.js 之前等待下载方法完成

[英]Wait for download method to finish before running next .then - node.js

我正在尝试通过构建一个允许用户下载文件的小应用程序来练习 node。

我已将文件保存在 S3 上,将 url 保存在 mLab 数据库中,并希望将文件下载到应用程序,以便我可以在客户端使用该 url 作为href 它目前可以工作,但下载一个空文件。 我认为这是因为它在文件下载之前正在运行下一个then()

这是我目前拥有的代码:

(async err => {
    const charge = await stripe.charges
      // create stripe charge
      .create({
       ...
      })
      // when the payment is successful, 
      // download the file locally to a 'dist' folder
      // so we can use it on the success page
      .then(() => {
        download(url_to_file, "dist").then(() => {
          console.log("done!");
        });
      })
      // then render the success page
      .then(
        res.render("success", {
          fileUrl: ...
        })
      )

因此,在客户端上,我可以(使用 ejs)执行以下操作:

<a href="<%= /dist/fileUrl %>">Download</a>

我对承诺很陌生,不知道如何在运行下一个 then 并呈现成功页面之前等待下载方法完全完成。

目前,该方法运行,然后成功页面呈现,然后文件出现在应用程序中。 这允许下载文件,但文件为空。

有人能指出我正确的方向/解释如何在运行下一个.then()方法之前等待下载完成吗? 任何帮助将不胜感激!

如果我没有记错的话,只需从download return承诺。

return

 Promise.resolve().then(()=> { new Promise(resolve => { setTimeout(() => { console.log('done 1'); resolve(); }, 1000); }); }).then(() => { console.log('done 2'); });

return

 Promise.resolve().then(()=> { return new Promise(resolve => { setTimeout(() => { console.log('done 1'); resolve(); }, 1000); }); }).then(() => { console.log('done 2'); });

暂无
暂无

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

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