Trying to form array of callback results from multiple sources of $.getJSON()

懵懂的女人 提交于 2019-12-25 02:55:13

问题


The code will process an array of calls from darkForecastAPIArray[] which go into the $.getJSON() but it will only return a single callback after processing the other calls indexed into the $.getJSON(). So after the code block is done I cannot get each instance of API requests into the array where it says APIResults.push(), it finishes the calls before it reaches the array and then it leaves only one callback on return. Any suggestions how to get all calls from the "result" into the following APIResults[] array? The whole script works somewhat like a form of indexing multiple JSON pages then placing them into an array to read each page of JSON. To simplify it appears to be finishing the $.getJSON method scope then do the callback once.

$.each(numDaysAPITimes, function(a, time) {
    darkForecastAPIArray.push(darkForecastAPI = /*"http://api.wunderground.com/api/" + currentAPIKey + "/history_" + time + "/q/" + state + "/" + city +".json?callback=?"; */
        "http://api.forecast.io/forecast/" + currentAPIKey + "/" + city + time + "?callback=?");
    console.log(darkForecastAPI);
});
//https://api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE,TIME
//$.each(darkForecastAPIArray, function(b, APICallRequest) {
    var deferreds = $.map(darkForecastAPIArray, function(url, index) {
        return $.getJSON(url, {
            tags: "WxAPI[" + index + "]",
            tagmode: "any",
            format: "json"
        });
    });
    $.when.apply($, deferreds).then(function(results) {
        $.each(results, function(index, data) {
            // do something

    APIResults.push(data);
    console.log(index);
    console.log(data);

        for (c = 0; c <= data.daily.data.length - 1; c += 1) {
            if (data.daily.data[c].precipIntensity >= 0.0000 && data.daily.data[c].precipType === "rain") /*Number(result.history.dailysummary.precipm, result.history.dailysummary.rain*/ {
                eachPrecipSum = data.daily.data[c].precipIntensity;
                totalPrecipSinceDate = eachPrecipSum + totalPrecipSinceDate; ///Write mean precip
                alert(Math.round(eachPrecipSum * 10000) / 10000);
                $("body").append("p").text("There has been as least a total of " + Math.round(totalPrecipSinceDate * 10000) / 10000 + " inches per hour of rain at the location in the last " + userDataDatePick + " days");

            } else if (data.daily.data[c].precipIntensity >= 0.0000 && data.daily.data[c].precipType !== "rain") {
                alert("There is was no rain on ____" /*+ result.history.dailysummary.mon + "/" + result.history.dailysummary.mday + "/" + result.history.dailysummary.year*/ );
              }
        }
    });
         });

numDaysAPITimes = 0;
}

回答1:


You are on the right track in your comment about using this recipe. Something like this should work:

var deferreds = $.map(urlArray, function(url, index) {
    return $.getJSON(url, {
        tags: "WxAPI[" + index + "]",
        tagmode: "any",
        format: "json"
    });
});
$.when.apply($, deferreds).then(function(results) {
    $.each(results, function(index, data) {
         // do something
    });
 });



回答2:


SOLUTION: Instead of using the loops that come with basic computer snippets I made a function level for() loop to solve the problem and broke the sections of code down into several functions. The functional level for() loop increments as each API call was made until it meets the number of elements. The function I simply named function done() {} The typical for() loop will terminate at its given scope so this one is unique and integrates the multiple callbacks which otherwise could not be used by using an array or deferred since deferreds or $.when() does not return multiple form arrays properly but with extraneous information that is hard to parse out. Here is the code:

function searchRainPrecip() {

            //.......more code........//

    $.each(numDaysAPITimes, function(a, time) {
        darkForecastAPIArray.push(darkForecastAPI = /*"http://api.wunderground.com/api/" + currentAPIKey + "/history_" + time + "/q/" + state + "/" + city +".json?callback=?"; */
            "http://api.forecast.io/forecast/" + currentAPIKey + "/" + city + time + "?callback=?");
     //   console.log(darkForecastAPI);
    });
    //https://api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE,TIME
          getDataCallbackResults();
    }


function getDataCallbackResults() { //call this function in loop for each call
    console.log(darkForecastAPIArray[z]);
    console.log(z);
    APIinstance = darkForecastAPIArray[z];
    $.getJSON(APIinstance, {
            tags: "WxAPI[" + f + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
            tagmode: "any",
            format: "json"
        },
        function(results) {
        APIResults.push(results);
        console.log(results.daily.data.length);
          processAPIPage(results);

        });       
}

function processAPIPage(results) {
            for (c = 0; c <= results.daily.data.length - 1; c += 1) {
                if (results.daily.data[c].precipIntensity >= 0.0000 && results.daily.data[c].precipType === "rain" && results.daily.data[c].time <= unixEpoch) /*Number(result.history.dailysummary.precipm, result.history.dailysummary.rain*/ {
                    eachPrecipSum = results.daily.data[c].precipIntensity;
                    console.log(eachPrecipSum);
                    totalPrecipSinceDate = eachPrecipSum + totalPrecipSinceDate; ///Write mean precip
                    alert(Math.round(eachPrecipSum * 10000) / 10000);
                    d = new Date(results.daily.data[c].time * 1000); //Convert to UTC  ~ SAVE FOR OTHER API SERVICES THAT USE UTC ~
                    curr_date = ("0" + d.getDate()).slice(-2);
                    curr_month = ("0" + (d.getMonth() + 1)).slice(-2); //Months are zero based
                    curr_year = d.getFullYear();
                    console.log(d.getMonth());

                    $("body").append("p").text("There has been as least a total of " + Math.round(totalPrecipSinceDate * 10000) / 10000 + " inches per hour of rain at the location in the since " + curr_month.toString() + "/" + curr_date.toString() + "/" + curr_year.toString());

                } else if (results.daily.data[c].time > unixEpoch) {
                    console.log(results.daily.data[c].time + " > " + unixEpoch);
                } else if (results.daily.data[c].precipIntensity >= 0.0000 && results.daily.data[c].precipType !== "rain" && results.daily.data[c].time <= unixEpoch) {
                    //Also can be named backDateEpochTime to convert next line; Get each day (UNIX seconds)
                    d = new Date(results.daily.data[c].time * 1000); //Convert to UTC  ~ SAVE FOR OTHER API SERVICES THAT USE UTC ~
                    curr_date = ("0" + d.getDate()).slice(-2);
                    curr_month = ("0" + (d.getMonth() + 1)).slice(-2); //Months are zero based
                    curr_year = d.getFullYear();
                    console.log(d.getMonth());

                    alert("There is was no rain on " + curr_month.toString() + "/" + curr_date.toString() + "/" + curr_year.toString());
                }
            }

    numDaysAPITimes = 0;
    result = null;
    done();
}

function done(){
//Global Function level for() loop or get point loops
    z += 1;
    if (z <= darkForecastAPIArray.length-1)
    {
    getDataCallbackResults()
    }
    else
    {
    console.log("All calculations complete.");
    }
}


来源:https://stackoverflow.com/questions/30091533/trying-to-form-array-of-callback-results-from-multiple-sources-of-getjson

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