Jef*_*ohn 7 javascript promise es6-promise
我使用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)")
Run Code Online (Sandbox Code Playgroud)
我想先执行.then函数,然后再执行console.log("this console should be executed after console.log(dataUrl)")。
请告诉我一些实现此目标的方法。
fre*_*due 12
有是当然的合法理由来迫使JS承诺的同步执行。最明显的是在require需要使用一些异步内容初始化的文件时,优化不是最重要的问题。
似乎包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")Run Code Online (Sandbox Code Playgroud)
对于现在绊脚石的那些人:
如果您不关心IE支持,则可以使用async和await来执行诺言,就好像它是同步的一样。该await语法将暂停功能的执行,直到承诺做出决议,让你写的代码,如果没有一个承诺。要捕获错误,请将其包装在一个try/catch块中。
唯一要注意的是,使用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)")
}
Run Code Online (Sandbox Code Playgroud)