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.
In JavaScript, promises are special objects that help you perform asynchronous operations. You can create a promise using the Promise constructor. You need to pass an executor function to it. In the executor function, you define what you want to do when a promise returns successfully or when it throws an error.
Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
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 function Promise. all runs in parallel. This makes it fast. However, there are situations where you want it to run synchronously, one after the other.
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")
Try this:
async function doStuff(arg) {console.log(arg + "Assume this is a useful async function")}
doStuff.apply(/* What to specify as this */ this, /* List of args */ ["hello world "])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With