回调完成后返回一个对象

时间:2013-02-22 20:11:17

标签: javascript extjs

调用此函数时,我希望函数在返回对象r之前等待回调完成

    function getWmsLayers(oneServerState){
            reader = new GeoExt.data.WMSCapabilitiesReader();;
            var serverLayers = new Array();
            var store = new GeoExt.data.WMSCapabilitiesStore({
                    url: OpenLayers.ProxyHost + oneServerState.serverUrl,
                    reader: reader
            });
            var isCallBackCompleted = false;
            store.load({
                    callback: function (r) {
                            return r;
                    }
            });
            //Do something ??
            return r;
    };


    layers = getWMSLayers(oneServerState);

2 个答案:

答案 0 :(得分:2)

您无法等待异步通话完成。这基本上是异步调用的定义!你能做的最好就是分裂你的调用逻辑。所以不要这样:

stuff();
result = doAsyncCall(); // WILL NOT WORK!
moreStuff(result);

使用这样的回调:

stuff();
var callback = function (result) { moreStuff(result); };
doAsyncCall(callback);

答案 1 :(得分:1)

你需要w8才能加载图层。像这样:

    function getWmsLayers(oneServerState, fnCallback){
            reader = new GeoExt.data.WMSCapabilitiesReader();;
            var serverLayers = new Array();
            var store = new GeoExt.data.WMSCapabilitiesStore({
                    url: OpenLayers.ProxyHost + oneServerState.serverUrl,
                    reader: reader
            });
            var isCallBackCompleted = false;
            store.load({
                    callback: function (r) {
                        fnCallback(r);
                    }
            });
    };

然后用这个函数调用这个函数:

    getWmsLayers(serverstate, function ( l ) {
       layers = l;
       nextFunctiontoContinueProgressing();
    });

这是建立回调链以完成请求的方法。