所以我试图在 JavaScript 中运行一个函数,但我需要在该函数开始之前运行并完成所有其他函数。这是代码(对不起,我知道它很长,但这是我可以说明正在发生的事情的唯一方法):
getWeather();
getAverage();
function getWeather() {
$.getJSON("http://where.yahooapis.com/geocode?q=" + lat + ",+" + lon + "&gflags=R&flags=J", function(data){
zipCode = data.ResultSet.Results[0].postal;
zipCode = zipCode.substring(0,5);
WOEID = data.ResultSet.Results[0].woeid;
getYahooWeather(WOEID);
getWeatherbug(zipCode);
getWeatherUnderground(zipCode);
getWorldWeather(zipCode);
});
}
function getYahooWeather(x) {
var query = escape('select item from weather.forecast where woeid="'+x+'"');
var url = "http://query.yahooapis.com/v1/public/yql?q=" + query + "&format=json";
$.getJSON(url, function(data2){
yahooTemp = data2.query.results.channel.item.condition.temp;
$("#yahoo-weather p").replaceWith("<p>Weather from Yahoo! powered by The Weather Channel = "+yahooTemp+"°F</p>");
});
}
function getWeatherbug(x) {
var url = "http://i.wxbug.net/REST/Direct/GetObs.ashx?api_key="+ weatherbugAPI + "&zip="+x+"&ht=t&ic=1&f=?";
console.log(url);
$.ajax({
url: url,
dataType: "jsonp",
success: function(data3) {
//console.log(data3.temperature);
wbTemp = data3.temperature;
$("#wb-weather p").replaceWith("<p>Weather from WeatherBug = "+wbTemp+"°F</p>");
}
});
}
function getWeatherUnderground(x) {
$.ajax({
url: "http://api.wunderground.com/api/b87325296cd69fa8/geolookup/conditions/q/IA/"+x+".json",
dataType: "jsonp",
success: function(parsed_json) {
var location = parsed_json['location']['city'];
wuTemp = parsed_json['current_observation']['temp_f'];
$("#wu-weather p").replaceWith("<p>Weather from Weather Underground = "+wuTemp+"°F</p>");
}
});
}
function getWorldWeather(x) {
var url = "http://free.worldweatheronline.com/feed/weather.ashx?key="+wwKey+"&q="+x+"&fx=no&format=json";
$.ajax({
url: url,
dataType: "jsonp",
success: function(data6) {
wwTemp = data6.data.current_condition[0].temp_F;
$("#ww-weather p").replaceWith("<p>Weather from World Weather Online = "+wwTemp+"°F</p>");
}
});
}
function getAverage() {
avTemp = wbTemp + wwTemp + yahooTemp + wuTemp;
console.log(avTemp);
}
我遇到的问题是,每当我运行 getAverage 函数时,它都会返回 NaN,因为其他函数还没有返回它们的数据。
有没有办法在所有以前的函数返回它们的数据之后运行一个函数?
谢谢