How make promise execute synchronously?

后端 未结 2 1377
闹比i
闹比i 2021-02-07 12:00

I use dom-to-image.js for converting dom to png image. As dom-to-image.js uses promise, the code executes asynchronously. I want to execute .then function synchronously.

2条回答
  •  臣服心动
    2021-02-07 12:18

    For those stumbling upon this now:

    If you're not concerned with IE support, you could use async and await to execute the promise as though it were synchronous. The await syntax will pause execution of the function until the promise resolves, letting you write the code as if there wasn't a promise. To catch an error, you wrap it in a try/catch block.

    The only catch is that using the await syntax requires you to wrap it inside a function declared with async.

    async function toPng() {
      try {
        let dataUrl = await domtoimage.toPng(document.getElementById("main"));
        console.log(dataUrl);
      }
      catch (error ) {
        console.error('oops, something went wrong!', error);
      }
    
      console.log("this console should be executed after console.log(dataUrl)")
    }
    

提交回复
热议问题