在继续之前解决 for 循环中的多个承诺

Resolve multiple promises within for loops before continuing

我有一个 angular 11 组件,它循环遍历页面元素,并将它们从 html > canvas > 图像转换。然后我将它们附加到表格中。

我的问题是承诺总是在 'done' 控制台日志运行后解决。在循环之后继续执行脚本之前,我如何 await 所有 generateCanvasFromHtml ?除了 运行 命令之外,此函数按预期运行

generateImagesFromPlan(): void {
    this.imageGenerating = true;

    // Create an empty for images to submit
    const formData = new FormData();

    // We get all the sections available on the plan
    const pdfSections = document.querySelectorAll('[data-pdfsection]');
    // tslint:disable-next-line:prefer-const
    for (let section of pdfSections as NodeListOf<HTMLElement>) {
      const sectionNumber = section.dataset.pdfsection;
      console.log('sectionName', sectionNumber)
      // We get all the partials available in the section (tables, headings, etc)
      const pdfComponents = section.querySelectorAll('[data-component]');
      console.log('pdfComponents', pdfComponents)
      // tslint:disable-next-line:prefer-const
      for (let element of pdfComponents as NodeListOf<HTMLElement>) {
        const componentImageNumber = element.dataset.component;
        console.log('componentName', componentImageNumber)
        // we create the image
        this.generateCanvasFromHtml(element).then(canvas => {
          canvas.toBlob((blob) => {
            formData.append(sectionNumber, blob, componentImageNumber + '.png');
            console.log('blob added');
          }, 'image/png');

        });
      }
    }

    for (let pair of formData.entries()) {
      console.log(pair[0] + ', ' + pair[1]);
    }
    console.log('done');
    this.imageGenerating = true;
  }

  generateCanvasFromHtml(elem: HTMLElement): Promise<HTMLCanvasElement> {
    // Put the content into an iframe with the width you want and you can obtain the actualy hegiht
    // Clone the element you want to capture
    const clone = elem.cloneNode(true);
    // Crate a dummy iframe
    const targetWidth = 1200;
    const iframe = document.createElement('iframe');
    iframe.style.visibility = 'hidden';
    iframe.width = targetWidth + 'px';
    iframe.height = '0px';
    document.body.appendChild(iframe);
    // Put cloned element into iframe
    const iframeDocument = iframe.contentDocument;
    iframeDocument.replaceChild(clone, iframeDocument.documentElement);
    // get scrollHeight of the iframe
    const targetHeight = iframeDocument.documentElement.scrollHeight;
    iframe.height = targetHeight + 'px';
    console.log('targetHeight=' + targetHeight);
    // Clean up
    document.body.removeChild(iframe);
    const options = {
      width: targetWidth,
      windowWidth: targetWidth,
      // Manually specify the height
      height: targetHeight
    };

    return html2canvas(elem, options);

  }

Promise.all 等待多个承诺。

因此,您需要做的是从 pdfComponents 创建一个包含 generateCanvasFromHtml() 个执行的数组,并将此数组提供给 Promise.all