How to get whole data out of callback function in javascript

核能气质少年 提交于 2019-12-11 03:52:43

问题


I have written following function which takes a json data from a url.

function getWeatherDataForCities(cityArray){
  var arrAllrecords = [];
  var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
  for(var i in cityArray){

    for(var j=1; j<=2; j++){
        var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;

        $.ajax({
            url: jsonurl,
            dataType: "jsonp",
            mimeType: "textPlain",
            crossDomain: true,
            contentType: "application/json; charset=utf-8",
            success: function(data){
              arrAllrecords[j]["cityName"] = data.list[0].city.name;
              arrAllrecords[j]["weather"] = data.list[0].weather[0].description;

        } });
        toDaysTimestamp = toDaysTimestamp - (24*60*60);
    }   
  }

  return arrAllrecords;  //returning arrAllrecords
}

$(document ).ready(function() {

  var cityArray = new Array();
  cityArray[0] = "pune";
  var arrAllRecords = getWeatherDataForCities(cityArray);
  //Print All records returned by getWeatherDataForCities(cityArray);
});

I have written some comments in above code.I have called getWeatherDataForCities function which returns all records from url.I have declared getWeatherDataForCities array in function.I want to add all returned records in that array.I have tried as above but nothing is getting into array.

In console showing j and arrAllrecords are undefined.

How to get all records in array from callback function?

you response will be highly appreciated


回答1:


Your getWeatherDataForCities function won't return anything because ajax operations are asynchronous. You need to use a callback for that.

Modify your function to accept a callback function:

function getWeatherDataForCities(cityArray, callback){
    var arrAllrecords = [];
    var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
    for(var i in cityArray){

       for(var j=1; j<=2; j++){
           var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;

            $.ajax({
                url: jsonurl,
                dataType: "jsonp",
                mimeType: "textPlain",
                crossDomain: true,
                contentType: "application/json; charset=utf-8",
                success: function(data){
                arrAllrecords[j]["cityName"] = data.list[0].city.name;
                arrAllrecords[j]["weather"] = data.list[0].weather[0].description;
                // call the callback here
                callback(arrAllrecords);
               } 
            });
           toDaysTimestamp = toDaysTimestamp - (24*60*60);
       }   
   }
}

And use it like this:

$(document ).ready(function() {
  var cityArray = new Array();
  cityArray[0] = "pune";
   getWeatherDataForCities(cityArray, function(arrAllrecords) {
       // Do something with your data
   });
});



回答2:


You are trying to use the empty array. When fetching the values it will always return you undefined.

var arrAllrecords = [];
arrAllrecords[2]; //undefined
arrAllrecords[2]["cityname"];  //undefined

Better you should use array of objects.

I don't know why you have used variable j. The below code works for me.

var arrAllrecords = [];

function getWeatherDataForCities(cityArray){

  var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
  for(var i in cityArray){

    var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;
        $.ajax({
            url: jsonurl,
            dataType: "jsonp",
            mimeType: "textPlain",
            crossDomain: true,
            contentType: "application/json; charset=utf-8",
            success: function(data){

            arrAllrecords.push({
                "cityName" : data.list[0].city.name,
                "weather" : data.list[0].weather[0].description

            });
            if(arrAllrecords.length === cityArray.length) {
                callback(arrAllrecords);
            }
        } });
  }
}

function callback(arrAllrecords) {
    console.log(arrAllrecords);
}


        $(document).ready(function() {

            var cityArray = new Array();
            cityArray[0] = "pune";
            cityArray[1] = "mumbai";
            cityArray[2] = "delhi";
            getWeatherDataForCities(cityArray);


        }); 


来源:https://stackoverflow.com/questions/20772502/how-to-get-whole-data-out-of-callback-function-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!