0

I need to return a value from within a function and that function pdf.create().tofile() always returns undefined. Now if I explicitly try to return a variable by making it global, I am not able to do it in typescript. Can someone help? Please refer as below:

var serviceS3Result: any;
await pdf
  .create(stocksReport({}))
  .toFile(`./dist/test.pdf`, async (err, res) => {
    if (err) console.log(err);
    console.log('hi from inside', res);
    serviceS3Result = await this.s3Service.uploadFileFromSystem(
      `test`,
      fs.readFileSync(`./dist/test.pdf`),
      `test.pdf`
    );
    fs.unlinkSync(`./dist/test.pdf`);
  });
return serviceS3Result;

this returns undefined, any idea why?

2
  • which library is used for pdf? At least from the snippet, it looks like the operation toFile accepts callback... Commented May 3, 2022 at 6:52
  • @NalinRanjan Sorry I did not mention it, it is the 'html-pdf' - link no it does not accept a callback only the HTML and the format of the converted pdf as said in the document. and yes toFile() accepts a callback but that is always returning undefined. Commented May 3, 2022 at 6:57

1 Answer 1

2

the .toFile call does not return a Promise, so await is actually useless here.

So the solution here is to wrap the call into a Promise then resolve the value:

return new Promise((resolve, reject) => {
    pdf.create(stocksReport({}))
        .toFile(`./dist/test.pdf`, async (err, res) => {
            if (err) reject(err);
            console.log('hi from inside', res);
            // The promise fulfills here
            resolve(await this.s3Service.uploadFileFromSystem(
                `test`,
                 fs.readFileSync(`./dist/test.pdf`),
                 `test.pdf`
            ));
            fs.unlinkSync(`./dist/test.pdf`);
        });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Small mistake: instead of res(await ... it should be resolve(
Good that you addressed the err handling as well in inside the callback.
@Taxel, KhanhBao.. Awesome! Thanks a lot! Learned something today.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.