正在使用异步请求初始化对象

Initializing object with asynchonous request

本文关键字:请求 初始化 对象 异步      更新时间:2023-09-26

这是我的对象定义:

function DrilledLayer(sourceLayerName, sourceTableName, targetLayerName, targetFieldName, operators, baseLayer=false) {
        this.sourceLayerName = sourceLayerName;
        this.sourceTableName = sourceTableName;
        this.targetLayerName = targetLayerName;
        this.targetFieldName = targetFieldName;
        this.operators = operators;
        this.baseLayer = baseLayer;
        this.targetLayerId;
        this.drilledLayerId;
        this.selectedCode;
        this.redraw = false;
        this.getTargetLayerId(); //this function must initialize this.targetLayerId
}
DrilledLayer.prototype.getTargetLayerId = function(){
  $.soap({
    url: 'https://url/version_4.8/services/MapService',
    method: 'getLayersIdByName',
    appendMethodToURL: false,
    data : {
        mapInstanceKey: mapKey,
        layerName: this.targetLayerName,
    },
    error: function(){
        alert("error getLayersIdByName");
    },
    success: function(soapResponse){
        layerId = soapResponse.toJSON().Body.getLayersIdByNameResponse.getLayersIdByNameReturn.getLayersIdByNameReturn.text;
        this.targetLayerId = layerId;
    }
  });
}

这就是我创建对象的方式:

drillCs = new DrilledLayer("Drilled CS", "Cs_Franco_General.TAB", "RA_General", "Code_RA", "=")

如果我查看drillCs对象,则没有定义targetLayerId属性,但我知道soap请求已成功发出。为什么?

JavaScript中的this主要由函数的调用方式设置。success回调期间的this与调用getTargetLayerId函数时的this不同,您必须记住

在这种情况下,最简单的方法可能是使用一个变量:

DrilledLayer.prototype.getTargetLayerId = function(){
  var layer = this;                     // <=== Set it
  $.soap({
    url: 'https://url/version_4.8/services/MapService',
    method: 'getLayersIdByName',
    appendMethodToURL: false,
    data : {
        mapInstanceKey: mapKey,
        layerName: this.targetLayerName,
        },
    error: function(){
        alert("error getLayersIdByName");
     },
    success: function(soapResponse){
        layerId = soapResponse.toJSON().Body.getLayersIdByNameResponse.getLayersIdByNameReturn.getLayersIdByNameReturn.text;
        layer.targetLayerId = layerId; // <=== Use it
        }
    });
}

更多(在我的博客上):

  • 你必须记住this

当然,另外,在异步回调触发之前(这将是new调用返回后的一段时间),您不会看到正确的,但您似乎对异步方面感到满意。