首页 > 解决方案 > 传单等待承诺解决

问题描述

我正在为某种缓存切片扩展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,传单没有问题和瓷砖正确显示。

标签: javascriptcachingpromiseleaflet

解决方案


这里的方法不是提供getLayerUrl方法,而是替换createTile元素的实现。

用原始实现替换实现的“noop”替换如下所示:createTilecreateTile

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)
  );

推荐阅读