How make promise execute synchronously?

余生长醉 提交于 2020-05-11 04:57:07

问题


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.

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

Please tell me some way to achieve this.


回答1:


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



回答2:


There are of 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.

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

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


来源:https://stackoverflow.com/questions/46273583/how-make-promise-execute-synchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!