Home > Mobile >  Global scope variables from within a function - Typescript
Global scope variables from within a function - Typescript

Time:05-03

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?

CodePudding user response:

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`);
        });
});
  • Related