我使用 dom-to-image.js 将 dom 转换为 png 图像。由于 dom-to-image.js 使用 promise,代码异步执行。我想同步执行 .then 函数。
我有以下代码:
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("this console should be executed after console.log(dataUrl)")
.请告诉我一些实现这一目标的方法。
最佳答案
当然,在 js 中强制同步执行 Promise 是有正当理由的。最明显的是当require
'ing 一个需要使用一些异步内容进行初始化的文件,并且优化不是最重要的问题。
好像是包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")
关于javascript - 如何让 promise 同步执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46273583/