承诺如何同步执行? [英] How make promise execute synchronously?

查看:50
本文介绍了承诺如何同步执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用dom-to-image.js将dom转换为png图像。当dom-to-image.js使用promise时,代码将异步执行。我想同步执行.then函数。

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.

我有以下代码:

domtoimage.toPng(document.getElementById("main")).then(function(dataUrl) {
    console.log(dataUrl);
}).catch(function(error) {
    console.error('oops, something went wrong!', error);
});

console.log("this console should be executed after console.log(dataUrl)")

我想先执行.then函数,然后再执行 console.log(此控制台应在console.log(dataUrl)之后执行)

I want to execute .then function first, before executing console.log("this console should be executed after console.log(dataUrl)").

请告诉我一些实现此目标的方法。

Please tell me some way to achieve this.

推荐答案

那些现在绊脚石的人:

如果您不关心IE支持,则可以使用异步并等待以执行承诺,就好像它是同步的一样。 await 语法将暂停函数的执行,直到承诺解决为止,让您像没有承诺一样编写代码。要捕获错误,请将其包装在 try / catch 块中。

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.

唯一的捕获是使用 await 语法要求您将其包装在用 async 声明的函数中。

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

这篇关于承诺如何同步执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆