在 canvas.ToBlob() 异步函数之外访问 blob 值 [英] access blob value outside of canvas.ToBlob() async function

查看:23
本文介绍了在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆