我正在使用HTMLCanvas元素,它返回异步toBlob()函数之外的blob对象.此函数不返回输出值,因此我尝试在外部声明变量并通过命令访问它.
我如何在这种情况下使用JS Promise?
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()访问Promise值
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)
});