async await in Angular 2

Viewed 265

I have a basic knowledge of await/async in Angular 2 following this exemple:

 async getValueWithAsync() {
    const value = <number>await this.resolveAfter2Seconds(20);
    console.log(`async result: ${value}`);
  }

In my Angular app I need to take a screenshot of a div, convert it to Blob, fetch an Amazon presigned URL from my backend and upload the screenshot client side with the presigned URL.

Each part of my logic is working and tested with PostMan. My issue is that the picture is uploaded before the function creating it returns it, resulting in an empty uploaded picture.

 async generateAnswer() {
    // takes a snaphot of the div and returns it as Blob
    var pic = await this.getPicture()
    // coonects to the backend and returns an Amazon S3 presigned Url
    this.s3Upload.getPresignedUrl("myPic")
      .subscribe(r => {
        // upload the snapshot as a Blob to my bucket 
        this.s3Upload.uploadFile(r["url"], pic)
          .subscribe(r => console.log("uploaded"))
      })
  }

  getPicture() {
    // takes a snaphot of the div and returns it as Blob
    return this.slideGenerator.generateAnswer()
  }

My generateAnswer():

generateAnswer() {
    let answer = document.querySelector('#answer') as HTMLImageElement;
    html2canvas(answer, { useCORS: true }).then(canvas => {
      var base64image = canvas.toDataURL("image/png");
      this.blobImage = this.dataURIToBlob(base64image);
      return (this.blobImage);
    });
  }

As I log pic I get undefined This logic is not working since it's not waiting for this.getPicture() to return a value before ploading it.

1 Answers

you can use await only in async functions, you should put await before anything that you wish to run synchronous (finish executing first)

async generateAnswer() {
  const answer = document.querySelector('#answer') as HTMLImageElement;
  const canvas = await html2canvas(answer, { useCORS: true });
  const base64image = canvas.toDataURL("image/png");
  this.blobImage = this.dataURIToBlob(base64image);//use await if async
  return this.blobImage;
}

and another thing, avoid using var, let when they are not necessary :)

Related