gpt4 book ai didi

javascript - 函数在变量定义之前返回

转载 作者:行者123 更新时间:2023-12-03 05:55:47 25 4
gpt4 key购买 nike

我有一系列简单的函数:

    convertXML();

function convertXML(){

var xmlObj = xmlToJson(xml.responseXML)
.query.results.WMS_Capabilities;
console.log("convertXML");

(function checkReturn(){
if(typeof xmlObj != 'undefined'){
return (function(){ return createData(xmlObj)})();
}
else {
setTimeout(checkReturn, 50);
}
})();
}

function createData(xmlObj){
for (var i = 0; i < xmlObj.Capability.Layer.Layer.length; i++){
var row={};
row = xmlObj.Capability.Layer.Layer[i];
WMSLayers.push(row);
};
console.log("createdata",WMSLayers)

return (function(){return finish()})();
}

function finish(){
console.log(n == Server.length-1)
if (n == Server.length-1){
//n is defined as an argument
//this code is a part of a bigger function
//same for Server variable
createTable();

};
}

问题是 convertXML 函数有时会返回带有 xmlObj 变量 undefined 的回调函数 createData 。所以我必须检查变量是否定义为调用回调函数。

我的问题是,当函数的所有变量都完成加载数据时,函数是否应该返回?

更新

这就是我提出请求的方式:

var req = {
"type" :"GET",
"dataType":"XML",
"data" : null,
"url" : url
};

//make the request (ajax.js)
ajax(req,ajaxSuccess,ajaxError);

function ajax(prop,onsuccess,onerror){
// data = data || null;
// var url = "wps"; // the script where you handle the form input.

$.ajax({
type: prop.type,
dataType: prop.dataType,
data: prop.data,
url: prop.url,
success: function (data, textStatus, xhr) {
console.log(xhr)
onsuccess(xhr);
},
error:function (data ,textStatus, xhr) {
onerror(xhr);
}

});
// e.preventDefault();
}

function ajaxSuccess(xhr){
$("#messages").append(
'<span style="color:blue">' +
getFullTime() +
'</span> Response HTTP status <b>' +
xhr.status +
' [' + xhr.statusText + ']' +
'</b> from:' +
' <a style="color:grey;text-decoration:none;" href="' +
url+
'" target="_blank">'+
Server[i].link +
Request["getCapabilities"]+
'</a><br>'
);

//create the wms
createWMS(xhr, Server[i],i);//this is where the convertXML,createData and finish functions are located

};

最佳答案

您可以使用$.get()complete函数。请注意,n 似乎没有在 finish 函数中定义。

function convertXML(xml, textStatus, jqxhr) {
var xmlObj = xmlToJson(jqxhr.responseXML)
.query.results.WMS_Capabilities;
console.log("convertXML");

if (typeof xmlObj != 'undefined') {
createData(xmlObj);
}
}

function createData(xmlObj){
for (var i = 0; i < xmlObj.Capability.Layer.Layer.length; i++){
var row = xmlObj.Capability.Layer.Layer[i];
WMSLayers.push(row);
};
console.log("createdata",WMSLayers)
finish();
}

$.get("/path/to/resource", convertXML, "xml")
.fail(function(jqxhr, textStatus, errorThrown) {
console.log(errorThrown)
});

关于javascript - 函数在变量定义之前返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39936061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com