我想生成多个pdf文件并附加到邮箱中.但await似乎不适用于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)
   ...
})

预期结果:

1
2
3
4

实际结果:

1
4
2
3

推荐答案

我认为res.app.render没有返回promise ,这就是您面临这个问题的原因.你必须做出一个定制的promise .我希望下面的代码会对您有所帮助.

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

Node.js相关问答推荐

promise 所有映射或反对

在我的Next.js应用程序中没有正确设置Process.env.NODE_ENV

根据我的测试,为什么在编写Varint代码方面,NodeJS要比Rust快这么多?

如何在ejs模板中使用循环显示多个结果?

findoneandupdate()方法更新数据库,但其响应在请求中返回为null

关于Node.js中的AES加密库的问题

NodeJS:zlib.gzipSync 在不同平台上给出不同的明文输出

表达 js 错误处理程序在第一个之后被忽略

如何使用对象中的常量值验证字符串字段?

在 linux mint 上部署 node 应用程序的最简单方法是什么?

在快速路由中使用 axios 会在数据字段中返回特殊字符而不是 json

将 express js app.use() 移动到另一个文件

node Axios 创建全局令牌变量以在单独的变量头中使用

如何在 NestJS 中使用外部生成的 swagger.json?

从数据库读取数据并将其作为可下载的 zip 文件发送

获取数组的至少一个元素包含子字符串的文档

如果 express.js (node.js) http 请求在完成之前关闭会发生什么?

node_modules 中 .bin 文件夹的用途是什么?

如果我使用像 express 这样的 node 服务器,是否需要 webpack-dev-server

在 Mongoose 中创建外键关系