在canvas.ToBlob()异步函数之外访问blob值 [英] access blob value outside of canvas.ToBlob() async function
本文介绍了在canvas.ToBlob()异步函数之外访问blob值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用HTMLCanvas
元素,该元素返回async toBlob()
函数外部的blob对象.该函数不会返回输出值,因此我试图在外部声明一个变量并通过命令访问它.
I'm working with HTMLCanvas
element that return the blob object outside of the async toBlob()
function. This function doesn't return an output value, so I'm trying to declare a variable outside and access it through the command.
在这种情况下如何使用JS Promise
?
How I can use JS Promise
for this scenario?
var myblob;
canvas.toBlob(function(blob) {
myblob = blob;
console.log("inside " + myblob); // getting value after the console outside
})
console.log( "outside " + myblob); // getting undefined
推荐答案
您可以使用Promise
构造函数,将Blob
实例传递给resolve()
,在.then()
You can use Promise
constructor, pass Blob
instance to resolve()
, access Promise
value at .then()
function getCanvasBlob(canvas) {
return new Promise(function(resolve, reject) {
canvas.toBlob(function(blob) {
resolve(blob)
})
})
}
var canvasBlob = getCanvasBlob(canvas);
canvasBlob.then(function(blob) {
// do stuff with blob
}, function(err) {
console.log(err)
});
这篇关于在canvas.ToBlob()异步函数之外访问blob值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文