0

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!

vnihoul
  • 41
  • 1
  • 8
  • The point of using `async` functions is to _not_ use `.then()` callbacks. – Phix Mar 24 '22 at 16:47
  • Are you taking each shot and then posting it, or are you grouping the shots and then posting them all at once? – Andy Mar 24 '22 at 16:54
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Liam Aug 11 '22 at 11:28

1 Answers1

2

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();
Andy
  • 61,948
  • 13
  • 68
  • 95