从另一个函数内部的回调函数返回值

问题描述 投票:0回答:2

我有一个函数被调用,需要返回一个值。该值存在于downloadOrders函数内部的回调函数中。问题是“go”(登录post request)在“关闭”之前打印(登录downloadOrders)。所以我无法返回encodedPdf值。我需要做什么?

app.post('/api/***', async (req, res) => {
    try {
        const result = await orderServices.downloadOrders(data);
        console.log("go")
        if(result){
            res.status(200).send(JSON.stringify(result));
        } else {
            res.status(400).send({err: 'Error creating PDF document.'});
        }
    } catch(err){
    }
});

async downloadOrders(data){
    try {

        let documents = ["sample.pdf"];
        const pdfStream = pdfmerger(documents);
        var writeStream = fs.createWriteStream('merged-pdf.pdf');
        pdfStream.pipe(writeStream);
        pdfmerger(documents, 'merged-pdf.pdf');
        pdfStream.on('close', function(code){
            console.log("close")
            let encodedPdf = base64.base64Encode('merged-pdf.pdf');
            return encodedPdf;
        });

    } catch(err){
        console.log(err)
        return false;
    }
}
javascript node.js asynchronous callback async-await
2个回答
1
投票

close事件包裹在Promise中,以便等待它。

await new Promise((resolve, reject) => {
  pdfStream
    .on('error', reject)
    .on('close', function(code){
      let encodedPdf = base64.base64Encode('merged-pdf.pdf');
      resolve(encodedPdf);
    });
});

0
投票

您也可以将downloadOrders函数包装在promise中。

app.post('/api/***', (req, res) => {
    orderServices.downloadOrders(data).then((result)=> {
        console.log("go")
        if(result){
            res.status(200).send(JSON.stringify(result));
        } else {
            res.status(400).send({err: 'Error creating PDF document.'});
        }
    }).catch(err => {
        res.status(500).send({err: 'Internal Server Error.'});
    });
});

const downloadOrders = function(data){
    return new Promise((resolve, reject) => {
      try {
        let documents = ["sample.pdf"];
        const pdfStream = pdfmerger(documents);
        var writeStream = fs.createWriteStream('merged-pdf.pdf');
        pdfStream.pipe(writeStream);
        pdfmerger(documents, 'merged-pdf.pdf');
        pdfStream.on('close', function(code){
            console.log("close")
            let encodedPdf = base64.base64Encode('merged-pdf.pdf');
            resolve(encodedPdf);
        });
        } catch(err){
          reject(err);
        }
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.