2

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?

SlothOverlord
  • 1,655
  • 1
  • 6
  • 16
  • 3
    `pdf.create()` might be synchronous, but the `.toBuffer()` function accepts a callback function as a parameter, which indicates that the callback function is called asynchronous. – Ivar Jul 13 '22 at 10:58
  • According to [the fine manual](https://github.com/marcbachmann/node-html-pdf#api), `pdf.create(input).toBuffer(callback)` is equivalent to `pdf.create(input, callback)` – robertklep Jul 13 '22 at 11:01
  • 2
    @Ivar. Your comment implies that anything that takes a callback is asynchronous. Which is clearly not the case – Jaromanda X Jul 13 '22 at 11:10
  • Thank you all for your insights, it helped me understand the callbacks more! I followed the answers above and managed to get it to work by promisifying the function and returning the data that way. – SlothOverlord Jul 13 '22 at 11:18
  • @JaromandaX True. I hoped that the "indicates" covered that it isn't necessarily always the case, but that might be poor wording on my part. In this case however, even without being familiar with the library used, I think it is safe to say that the callback _is_ asynchronous. – Ivar Jul 13 '22 at 11:20
  • @Ivar i agree ... specially as it's in the (err, result) format – Jaromanda X Jul 13 '22 at 11:22

0 Answers0