访问canvas.ToBlob()异步函数之外的blob值

时间:2017-02-25 16:54:11

标签: javascript html promise

我正在使用HTMLCanvas元素来返回async 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   




3 个答案:

答案 0 :(得分:5)

您可以使用Promise构造函数,将Blob实例传递给resolve(),访问Promise处的.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)
});

答案 1 :(得分:5)

const blob = await new Promise(resolve => canvasElem.toBlob(resolve));

答案 2 :(得分:1)

我还有另一种想法...与标记为最佳想法的想法类似... 然后存在的问题是,您必须位于区块内才能从诺言。现在Javascript支持类似于c#的 await ,这很好,因为您可以运行该函数并等待其解析,然后将结果返回未绑定到任何函数的变量,例如:

/* basically we create a function that receives a canvas called mycanvas, then we tell the function to return a new Promise, this promise is "resolved" inside the .toBlob method which by default provides a Blob parameter. */

function getCanvasBlob(mycanvas) {
  return new Promise(function(resolve, reject) {
    mycanvas.toBlob((blob) => {
      resolve(blob)
    })
  })
}

var myblob;

try{
  myblob = await getCanvasBlob(CANVAS_FROM_SOMEWHERE);
}
catch (error){
  console.log(error);
}

/* There's no need to use try/catch, you could use it just like this */

var myblob = await getCanvasBlob(CANVAS_FROM_SOMEWHERE);

由于该方法是异步的,因此在承诺被解决之前,将不会执行或调用 then(),直到该方法之外的任何更改都不会被通知,直到为时已晚为止。是我们的javascript直到完全解决了诺言之后才会继续。

附加信息:如果您调用await,则调用此函数的方法必须标记为异步,否则您将看到错误...可以说例如在单击按钮时调用此方法:< / p>

/* OBVIOUSLY this will throw an error because I don't have a real canvas...*/

$( document ).ready(function() {
    
    $('#mybutton').bind('click', async function(){
    
      //...more code...
      //...more code... until...
      
      var CANVAS_FROM_SOMEWHERE;
      
      var myblob = await getCanvasBlob(CANVAS_FROM_SOMEWHERE);
    
    });
    
});

function getCanvasBlob(mycanvas) {
  return new Promise(function(resolve, reject) {
    mycanvas.toBlob((blob) => {
      resolve(blob)
    })
  })
}

   

    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="mybutton">process my canvas!</button>