How make promise execute synchronously?

后端 未结 2 1525
闹比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:17

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

提交回复
热议问题