I'm quite confused about this code as it should behave sync, but it doesn't return data in time.
In my experience, the following should happen:
- pdf.create is called
- blob and pdfSize is set
- console.log(BLOB AND SIZE)
- console.log(BLOB AND SIZE OUTSIDE)
- uploadFile
But this is what really happens:
- pdf.create is called
- console.log(BLOB AND SIZE OUTSIDE) (undefined)
- uploadFile (Throws an error)
- blob and pdfSize is set
- console.log(BLOB AND SIZE)
I am using html-pdf node package
resolve: async (parent, args, { req }) => {
try {
//...
let blob = undefined;
let pdfSize = 0;
const pdfId = uuidv4();
pdf.create(args.data.htmlTemplate, {
//...
})
.toBuffer((err, buffer) => {
if (err) {
console.log(err);
}
blob = Buffer.from(buffer).toString('base64') as unknown as Blob;
pdfSize = Buffer.byteLength(buffer);
console.log('BLOB AND SIZE: ', blob, pdfSize);
});
console.log('BLOB AND SIZE OUTSIDE: ', blob, pdfSize);
await uploadFile(pdfId, blob as unknown as string, 'application/pdf');
//...
} catch (error) {
console.error(JSON.stringify(error, null, 2));
if (error instanceof Error) {
throw new Error(error.message);
}
}
},
There are no indication by typescript that .pdfCreate is async or a promise, and awaiting it does not work.
Im I not understanding the function chaining correctly?
How can I get to to work in the order I mentioned above?