我有一个函数被调用,需要返回一个值。该值存在于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;
}
}
将close
事件包裹在Promise
中,以便等待它。
await new Promise((resolve, reject) => {
pdfStream
.on('error', reject)
.on('close', function(code){
let encodedPdf = base64.base64Encode('merged-pdf.pdf');
resolve(encodedPdf);
});
});
您也可以将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);
}
});
}