为什么我的javascript Promise卡住为“待处理”? [英] Why is my javascript Promise stuck as "pending"?
问题描述
我有一个绘制到画布上的复杂SVG,并且此任务需要在绘制其他对象之前完成。这是一个模拟的小提琴:
I have a complex SVG that is drawn to a canvas, and this task needs to complete before other objects are drawn. Here's a fiddle simulating this:
https:// jsfiddle .net / 1hucuLg9 / 1 /
//draw svg
var promise = new Promise(function(){
drawSwatch(document.getElementById("mySwatch"));
//not typo, canvas context is referenced inside this function due to xml complexity in this fiddle
});
//draw image
promise.then(function(){
ctx.drawImage(document.getElementById("myImg",0,0,150,150));
});
在小提琴中您会注意到,仅绘制了SVG,之后未绘制其他图像。用于绘制SVG的 Promise
被卡为待处理...即使内部javascript全部执行了。
You'll note in the fiddle that only the SVG is drawn, not the other image afterwards. The Promise
used to draw the SVG is stuck as pending ... even though the inner javascript is all executed. What's going on?
推荐答案
如果只想添加 myImg
次 drawSwatch
中的图像已加载-您可以执行此操作
If you want to add myImg
only once the image inside drawSwatch
has loaded - you can do this
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
//hard code variables for example
var vw=300, vh=200, x=20, y=50, w=250, h=50; rx=10, ry=5, bg="#fae", theta=15, midptX=100, midptY=120, blur=5;
//helper function to draw swatch objects
function drawSwatch(currentSwatch, resolve){ // extra parameter
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="'+vw+'" height="'+vh+'">'+
'<defs>'+
'<filter id="f1">'+
'<feGaussianBlur in="SourceGraphic" stdDeviation="'+blur+'" />'+
'</filter>'+
'</defs>'+
'<rect class="shape" x="0" y="0" width="'+w+'" height="'+h+'" rx="'+rx+'" ry="'+ry+'" transform="translate('+x+','+y+') rotate('+theta+','+midptX+','+midptY+')" fill="'+bg+'" filter="url(#f1)"></rect>'+
'</svg>';
//now draw the svg to canvas
var svg_data = encodeURIComponent(data);
// create a dataURI version
var url = 'data:image/svg+xml; charset=utf8, ' + svg_data;
var img = new Image();
img.onload = function(){
ctx.drawImage(img, 0, 0, vw, vh);
resolve(); // call the passed in resolve function
}
img.src = url;
}
//draw svg
var promise = new Promise(function(resolve){
drawSwatch(document.getElementById("mySwatch"), resolve); // call drawSwatch passing in the resolve function
});
promise.then(function(){
ctx.drawImage(document.getElementById("myImg"),0,0,150,150);
});
在 drawSwatch
中添加了第二个参数是promise构造函数中的 resolve
函数
added a second parameter to drawSwatch
, which is the resolve
function from the promise constructor function
现在promise中的回调函数。直到 img.onload
被触发
Now the callback in promise.then wont be called until img.onload
is fired
工作中的小提琴-在小提琴中,不是直接调用resolve,而是将其放在setTimout中,以显示。然后
不是在诺言真正得到解决之前不会执行
working fiddle - in the fiddle, instead of calling resolve directly, I've put it in a setTimout, to show that .then
isn't executed until the promise is actually resolved
这篇关于为什么我的javascript Promise卡住为“待处理”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!