sync function behaves as async. How can I await it?

Viewed 37

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:

  1. pdf.create is called
  2. blob and pdfSize is set
  3. console.log(BLOB AND SIZE)
  4. console.log(BLOB AND SIZE OUTSIDE)
  5. uploadFile

But this is what really happens:

  1. pdf.create is called
  2. console.log(BLOB AND SIZE OUTSIDE) (undefined)
  3. uploadFile (Throws an error)
  4. blob and pdfSize is set
  5. 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?

0 Answers
Related