简体   繁体   中英

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

I am trying to practice node by building a small application that allows a user to download a file.

I have saved the file on S3, saved the url in a mLab DB, and want to download the file to the app so I can use the url as an href on the client side. It currently works, to a point, but downloads an empty file. Which I think is due to the fact that it is running the next then() before the file has downloaded.

This is the code I currently have:

(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: ...
        })
      )

So on the client I can (using ejs) do something like:

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

I am very new to promises and not sure how to wait for the download method to completely finish before running the next then and rendering the success page.

At the moment, the method runs, then the success page renders, then the file appears in the app. This allows the file to be downloaded but the file is empty.

Can anybody point me in the right direction / explain how to wait for the download to finish before running the next .then() method? Any help would be massively appreciated!

If I'm not mistaking, just return the promise from the download .

Without return

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

With return

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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