【发布时间】:2021-11-11 00:10:55
【问题描述】:
我有一个使用 OpenLayers 的 Vue 2 无服务器 Web 应用程序。我遇到了一个有趣的编程问题,该问题也适用于其他应用程序,我需要多次按顺序执行 3 个方法。
for(let i = 0 ; i < this.dateArraySurface10.length - 1 ; i++)
{
waterfall([
this.setTimeSurface10(),
this.map.renderSync(),
this.myCallback(),
],
function(err){
console.log("Waterfall done",err);
});
}
这是我尝试调用执行以下三件事的三个函数
-
this.setTiimeSurface10():更新已添加到地图中的 ImageWMS 源图层的TIME参数。 -
this.map.renderSync():是在全局地图对象上调用的 OpenLayers 方法,以确保渲染所有图层。 -
this.myCallback(): 是一个提取地图画布并将其作为框架添加到 GIF 对象的函数。
我的问题是我需要这三种方法以该顺序运行 72 次,尽管我可以使用 setTimeout 对它们进行硬编码,但我需要一种更抽象的方法来执行此操作,以便允许用户添加许多图层并导出为 GIF无论。我试图在this.map 对象上添加一个事件监听器,但有些东西不能正常工作。
如何以最纯粹的 Javascript 方式以编程方式确保所有三个方法在 for 循环中按顺序执行?
如果有帮助,这里有两种方法:
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});
}
【问题讨论】:
-
作为一般提示,JS 中的异步任务最常通过
Promises或async和await关键字(基本上只是Promises的语法变体)来处理。在这种情况下,通过创建一个 rendercomplete-listener 来同步工作可能就足够了,并且在这个 listener 中更新你的 time 参数。该 rendercomplete-listener 也可以在完成后自行移除。
标签: javascript vue.js asynchronous openlayers