javascript 如何让promise同步执行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46273583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:33:38  来源:igfitidea点击:

How make promise execute synchronously?

javascriptpromisees6-promise

提问by Jeffrin John

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.

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

I have the following code:

我有以下代码:

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

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

我想先执行 .then 函数,然后再执行 .then 函数console.log("this console should be executed after console.log(dataUrl)")

Please tell me some way to achieve this.

请告诉我一些方法来实现这一点。

回答by Steven Lambert

For those stumbling upon this now:

对于那些现在遇到这个问题的人:

If you're not concerned with IE support, you could use async and awaitto execute the promise as though it were synchronous. The awaitsyntax 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/catchblock.

如果您不关心 IE 支持,您可以使用async 和 await来执行承诺,就像它是同步的一样。该await语法将暂停功能的执行,直到承诺做出决议,让你写的代码,如果没有一个承诺。要捕获错误,请将其包装在一个try/catch块中。

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

唯一的问题是使用该await语法需要您将其包装在用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)")
}

回答by fresidue

There areof course legit reasons to force synchronous execution of a promise in js. The most obvious is when require'ing a file that needs to initialize using some asynchronous stuff, and optimization is not an overriding concern.

当然的合法理由来迫使JS承诺的同步执行。最明显的是在require需要使用一些异步内容初始化的文件时,优化不是最重要的问题。

Seems like the package synchronized-promiseseems like it ought to do the trick. In your case (warning - untested..):

似乎包synchronized-promise似乎应该可以解决问题。在你的情况下(警告 - 未经测试..):

const dti = () => docstoimage.toPng(document.getElementById("main"))
  .then(dataUrl => console.log('url: ', dataUrl))
  .catch(err => console.error('oops: ', err))

const sp = require('synchronized-promise')
const syncDti = sp(dti)
syncDti() // performs the 'synchronized version'

console.log("this console should be executed afterwards")