javascript - 传单等待承诺解决
问题描述
我正在为某种缓存切片扩展Leaflet getTileUrl 。我使用 Vue,但它不应该影响任何东西。它目前看起来像这样:
//step 1
L.TileLayer.MyLayer = L.TileLayer.extend({
getTileUrl: function(coords) {
var url = this.getLayerUrl(coords.z, coords.x, coords.y);
return url;
}.bind(this)
});
//step 2
L.tileLayer.myLayer = function() {
return new L.TileLayer.MyLayer();
}
//step 3
L.tileLayer.myLayer().addTo(this.getParent('main-map').map);
问题是getLayerUrl函数返回一个承诺。即使我尝试使getTileUrl 异步,而不是等待this.getLayerUrl (并且也使异步等待第 2 步和第 3 步)或在 this.getLayerUrl 之后放置.then(function(result) {return result;},Leaflet 在浏览器中显示错误控制台尝试从 url 获取图块:GET http://localhost/project/public/[object%20Promise]
另外我应该提到 this.getLayerUrl 为每个图块返回不同的 url,它实际上是一个 blob url,如:blob:http://localhost/f7c4298f-9e9d-423f-9d0b-3f7a301e433f 但如果正确返回了 url,传单没有问题和瓷砖正确显示。
解决方案
这里的方法不是提供getLayerUrl
方法,而是替换createTile
元素的实现。
用原始实现替换实现的“noop”替换如下所示:createTile
createTile
L.TileLayer.MyLayer = L.TileLayer.extend({
getTileUrl: function (coords) {
var tile = document.createElement("img");
DomEvent.on(tile, "load", Util.bind(this._tileOnLoad, this, done, tile));
DomEvent.on(tile, "error", Util.bind(this._tileOnError, this, done, tile));
if (this.options.crossOrigin || this.options.crossOrigin === "") {
tile.crossOrigin =
this.options.crossOrigin === true ? "" : this.options.crossOrigin;
}
tile.alt = "";
tile.setAttribute("role", "presentation");
tile.src = this.getTileUrl(coords);
return tile;
}
});
考虑到该实现,可以以异步方式设置的src
属性,将HTMLImageElement
同步替换为tile.src = this.getTileUrl(coords);
例如:
asyncGetLayerUrl(coords)
.then(function (url) {
tile.src = url;
})
而且,为了更好地衡量,通过调用来处理承诺拒绝this._tileOnError
,例如:
asyncGetLayerUrl(coords)
.then(function (url) {
tile.src = url;
})
.catch(
function (err) {
this._tileOnError(done, tile, err);
}.bind(this)
);
推荐阅读
- node.js - Sequelize - 同步多对多
- c# - 解析从流加载的 libvlcsharp 视频不起作用
- c++ - 如何解决这两个错误?'strlwr' - '但参数 2 的类型为 'int''
- symfony - Symfony:如何在编辑功能上检查控制器中的多种字符串类型
- android - 错误:ADB 以退出代码 1 退出 启动应用程序时出错
- python - 是否有特定的方法可以在 python 中的某个时间打开 Web 链接?
- database - '在 SQL 语句结束后找到的字符。'
- python - 在 macOS 11.0 Big Sur 上安装 Pyobjc 时出错
- vba - 如何在 Access 中使用 VBA 连接多个 Salesforce 实例
- angular - Why am I getting an "undefined" error when returning a string with a callback in Typescript?