Angular 使用 html2canvas 并等待其完成(异步/等待?)

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

我有一个问题,我需要按特定顺序 运行 2 个方法,等待第一个方法完成,然后 运行 完成第二个方法。

以下是这 2 个示例方法:

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');
}

我运行这样对待他们:

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

我想我应该使用 async/await ?

如何在 Angular 12 中执行此操作?

是的,您可以使用 async/await。这是您更改代码的方式:

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');
  })
  
}

当你有一些异步的东西时,你总是可以遵循这些步骤。您可以创建一个承诺,您可以 resolve/reject 它基于结果。