Search code examples
angularasync-awaitangular12

Angular using html2canvas and waiting until its completed (async / await?)


I have an issue where I need to run 2 methods in a specific order, waiting for the first one to complete before running the second one.

Here are these 2 sample methods:

part1() {
  const element = document.getElementById("capture") as HTMLCanvasElement;
  html2canvas(element).then((canvas) => {
    this.thecanvas = canvas.toDataURL();
    console.log('Dont do part2 until the.thecanvas is populated');
  });
}


part2() {
  // do other stuff but only after part1 is completed
  console.log('All completed');
}

I'm running them like this:

main() {
    // I need them to run in this sequence
    this.part(); // first
    this.part2(); // last
}

I'm guessing I should use async/await ?

How do I do this in Angular 12?


Solution

  • Yes, you can use async/await. This is how you change your code:

    part1() {
      const element = document.getElementById("capture") as HTMLCanvasElement;
    
      return new Promise(async (resolve, reject) => {
          try {
            const canvas  = await html2canvas(element)
            this.thecanvas = canvas.toDataURL();
            console.log('Dont do part2 until the.thecanvas is populated');
            // when you complete the things successfully, you shoule call resolve else call reject
            resolve('Dont do part2 until the.thecanvas is populated'); 
          } catch (error) {
            reject(error);
          }
          
      })
     
    }
    
    part2() {
      // do other stuff but only after part1 is completed
    
      return new Promise((resolve, reject) => {
          console.log('All completed'); 
          // when you complete the things successfully, you shoule call resolve else call reject
          resolve('All completed');
      })
      
    }
    

    You can always follow these steps when you have something async in nature. You can create a promise and you can resolve/reject it based on the results.