从具有回调函数的函数返回一些东西

时间:2014-08-11 20:14:54

标签: jquery

我的函数没有返回任何内容,因为它是异步的。我如何退回viallages?

function getVillages() {
    var self = this;
    this.a = [];
    VCare.VCareWebService.getFacilitiesForUser({cache:false,
        callback:function(xml) { // invoke the service
            // use jQuery to extract information we are interested in
            console.log(xml);
            var village = xml.getElementsByTagName("VCVillage");
            for (i=0;i<village.length;i++) { 
                self.a.push(village[i].getElementsByTagName("description")[0].childNodes[0].nodeValue); // Uncaught TypeError: Cannot call method 'push' of undefined 
                console.log(village[i].getElementsByTagName("description")[0].childNodes[0].nodeValue);
            }

        }
   });
    console.log(self.a);
    //return(allVillages);
}

尝试制作一个村庄对象并给它一个allVillages属性并更新它:

function Villages() {
    this.allVillages = [];
}

function getVillages(village1) {
    VCare.VCareWebService.getFacilitiesForUser({cache:false,
        callback:function(xml, village1) { // invoke the service
            // use jQuery to extract information we are interested in
            console.log(xml);
            var village = xml.getElementsByTagName("VCVillage");
            for (i=0;i<village.length;i++) { 
                village1.allVillages.push(village[i].getElementsByTagName("description")[0].childNodes[0].nodeValue);
                console.log(village[i].getElementsByTagName("description")[0].childNodes[0].nodeValue);
            }
            if(typeof callback === "function") callback(xml);
        }
   });
    //return(allVillages);
}

function addVillages(){

village = new Villages();
console.log(village); //Villages {allVillages: Array[0]}

getVillages(village);
console.log(village.allVillages); //[]
for (i=0; i < data; i++) {
    console.log(data[i]);
    console.log(data[i][1]);
}

}

我得到Uncaught TypeError: Cannot call method 'push' of undefined因为village1似乎未定义。但我确实传递了一个正确的村庄对象

1 个答案:

答案 0 :(得分:0)

此页面上的技术How to get return value in a function with inside Ajax call - JQuery

这是工作代码:

function getVillages(callback) {
         var data = [];
        VCare.VCareWebService.getFacilitiesForUser({cache:false,
            callback:function(xml) { // invoke the service
                // use jQuery to extract information we are interested in
                console.log(xml);
                var village = xml.getElementsByTagName("VCVillage");

                for (i=0; i<village.length; i++) {
                    data.push(village[i].getElementsByTagName("description")[0].childNodes[0].nodeValue);
                }

                if (typeof callback === "function") callback(data);            
            }
       });
    }

function addVillages() {
    var data = getVillages(function(data){
        for (i=0; i < data.length; i++) {
            //do whatever you want with the data
        }
    });
}