Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

await not working on res.app.render in Express.js

I want to generate multiple pdf files and attach to the email. But await seems not working on res.app.render.

route.get('/:id/receipts', async function (req, res) {
   ...
   let attachments = [];
   for await(let item of items){
      res.view.item = item;
      console.log(1)
      await res.app.render('pdfs/receipt', res.view, async function(err, html){
         console.log(2)
         if (err) return res.end(err.stack)
         return await pdf.create(html).toBuffer(async function(err, buffer){
            console.log(3)
            attachments.push({
               content: buffer,
               filename: 'receipt.pdf',
           })
         });
      });
   }
   console.log(4)
   ...
})

Expect Result:

1
2
3
4

Actually Result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1
4
2
3

>Solution :

I think res.app.render is not returning a promise that’s why you are facing this issue. You have to make a custom promise. I hope following code will help you.

    oute.get('/:id/receipts', async function (req, res) {
    ...
    let attachments = [];
    for await(let item of items){
    res.view.item = item;
    console.log(1)
    const customPromise = new Promise((resolve, reject) => {
            res.app.render('pdfs/receipt', res.view, async function(err, html){
            console.log(2)
            if (err) { res.end(err.stack);reject()}
            else {
                await pdf.create(html).toBuffer(async function(err, buffer){
                    console.log(3)
                    attachments.push({
                        content: buffer,
                        filename: 'receipt.pdf',
                    })
                });
                resolve();
            }
    });
    })
    }
    console.log(4)
    ...
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading