Search code examples
javascriptasynchronousasync-awaitpromisehtml2canvas

Wait for a promise to be resolved before continuing with function


I know this has been asked many times, but the async/promise concept is very obscure to me! I am trying to take a screenshot using html2canvas and once the (or multiple) screenshots are generated, continue with the function and send it through a POST request.

Here's what I've done so far:

async function take_screenshot1() {
    const screenshotTarget = document.body;
    const screenshot1 = html2canvas(screenshotTarget).then((canvas) => {
    const screenshot1 = canvas.toDataURL();
    return screenshot1
});
    return screenshot1
}

var screenshot1 = take_screenshot1()

And

async function take_screenshot() {
  return new Promise((resolve, reject) => {
      setTimeout(() => {
        const screenshotTarget = document.body;
        var result = html2canvas(screenshotTarget).then((canvas) => {
    const screenshot1 = canvas.toDataURL();
});
        resolve(result);
      }, 300);
  });
}

  var screenshot = await take_screenshot();
  console.log(`After await: ${screenshot}`);
  console.log("I expect to be after the values");

If someone could give me some advice about where I get things wrong, I would appreciate it! Thanks for your time!


Solution

  • It depends on how your grouping your data but this is a simple example. async functions return a promise so you need to await them too.

    const { body } = document;
    
    async function takeScreenshot() {
      const screenshot = await html2canvas(body);
      return screenshot.toDataURL();
    }
    
    async function main() {
      const canvas = await takeScreenshot();
      body.appendChild(canvas);
    }
    
    main();