我正在嘗試使用 pdfkit 創建多個 PDF 檔案,我有一組用戶,我為每個用戶創建一個報告,createTable()下面的函式回傳一個Buffer我發送給存檔器的壓縮檔案,一旦完成,壓縮檔案被發送下載到前端。
我的問題是,由于某種原因,Archiver 有時會拋出QUEUECLOSED錯誤,如果我運行該函式太多次,有時我可以運行 10 次,第 11 次我會收到錯誤,有時我會在第二次之后收到錯誤時間,每次我運行它的資料都是一樣的,沒有其他改變。
任何幫助是極大的贊賞。
users.forEach(async (worker, index) => {
createTable(date, worker.associateName, action, worker.email, worker.id, excahngeRate).then(resp => {
archive.append(resp, { name: worker.associateName '.pdf' })
if (index === users.length - 1 === true) {//make sure its the last item in array
archive.pipe(output)
archive.finalize();
}
}).catch(err => {
console.log(err)
})
});
uj5u.com熱心網友回復:
你完成得太早了。最后一個用戶的 createTable 可能不是最后一個完成的。您應該將所有內容添加到存檔中,一旦完成,請完成它。
// Use map to get an array of promises
const promises = users.map(async (worker, index) => {
return createTable(date, worker.associateName, action, worker.email, worker.id, excahngeRate).then(resp => {
archive.append(resp, { name: worker.associateName '.pdf' })
}).catch(err => {
console.log(err)
})
});
// Wait for all promises to finish.
Promise.all(promises).then(()=>{
archive.pipe(output)
archive.finalize();
});
在您當前的代碼中,您可以在 IF 陳述句之前使用 console.log,并記錄已完成的 createTable 的索引,您會看到它們沒有按順序完成。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/503695.html
標籤:javascript 节点.js 节点归档
