在继续功能之前等待承诺得到解决

Wait for a promise to be resolved before continuing with function

我知道这个问题已经被问过很多次了,但是 async/promise 这个概念对我来说很晦涩! 我正在尝试使用 html2canvas 截取屏幕截图,一旦生成(或多个)屏幕截图,继续使用该功能并通过 POST 请求发送它。

这是我目前所做的:

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()

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");

如果有人能给我一些错误的建议,我将不胜感激! 感谢您的宝贵时间!

这取决于您如何对数据进行分组,但这是一个简单的示例。 async 实现 return 承诺,因此您也需要等待它们。

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();