【发布时间】:2021-12-24 20:32:31
【问题描述】:
我正在尝试创建一个 for 循环,该循环在每次迭代时更新 OpenLayers 地图的参数,一旦它是renderedcomplete,它就会提取地图画布的上下文并将其添加到 GIF 对象中。我需要这些同步运行,以便始终允许渲染地图和图层,然后才能添加上下文。目前我的 hacky 解决方案是使用固定时间 setInterval,但正如 question 中所建议的那样,我应该使用 async/await/Promises。我的问题是如何将我的函数包装在 Promise 中并确保它们按顺序执行,同时保持对 vue 应用程序上下文 (this) 的访问?
我的 for 循环看起来像:
for(let i = 0 ; i < this.dateArraySurface10.length - 1 ; i++)
{
waterfall([
this.setTimeSurface10(),
this.map.renderSync(),
this.myCallback(),
],
function(err){
console.log("Waterfall error : ",err);
});
}
函数在哪里:
setTimeSurface10: function () {
if (this.currentTimeSurface10 === null) {
this.currentTimeSurface10 = this.startTimeSurface10;
} else if (this.currentTimeSurface10 >= this.endTimeSurface10) {
this.currentTimeSurface10 = this.startTimeSurface10;
} else {
this.currentTimeSurface10 = new Date(
this.currentTimeSurface10.setMinutes(this.currentTimeSurface10.getMinutes() + 60)
);
}
this.surface10.getSource().updateParams({ TIME: this.currentTimeSurface10.toISOString().split(".")[0] + "Z" });
},
myCallback: function () {
const mapCanvas = document.createElement('canvas');
const divElement = document.querySelector(".map");
mapCanvas.width = divElement.offsetWidth;//size[0];
mapCanvas.height = divElement.offsetHeight;//size[1];
const mapContext = mapCanvas.getContext('2d');
Array.prototype.forEach.call(
document.querySelectorAll('.ol-layer canvas'),
function (canvas) {
if (canvas.width > 0) {
const opacity = canvas.parentNode.style.opacity;
mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity);
const transform = canvas.style.transform;
const matrix = transform
.match(/^matrix\(([^\(]*)\)$/)[1] //eslint-disable-line
.split(',')
.map(Number);
CanvasRenderingContext2D.prototype.setTransform.apply(mapContext,matrix);
mapContext.drawImage(canvas, 0, 0);
}
}
);
this.gif.addFrame(mapCanvas, {copy:true, delay: 200});
}
【问题讨论】:
标签: javascript vue.js asynchronous promise openlayers