【发布时间】:2017-06-29 13:44:27
【问题描述】:
您好,我有两个针对天气项目的 JSON 请求,我需要来自第一个请求的数据,以便为用户个性化第二个请求。我的第一个请求获取用户的纬度和经度,第二个请求获取该位置当前天气的 url 中的坐标。
var arrLocat = [];//users suburb, city, country, lat and lon
var userURL = "";//specific url tailored off users lat and lon
var userWeather = [];//current weather at users lat and lon
$(document).ready(function(){
//first JSON request
$.getJSON("http://ip-api.com/json", function (data){
arrLocat = data;
userURL = "http://api.openweathermap.org/data/2.5/weather?lat=" + arrLocat.lat + "&lon=" + arrLocat.lon + "&appid=61c4ebe6f40d2e2d7085e7c42d287e1d&units=metric";
console.log(arrLocat);THIS RETURNS FIRST, WORKS FINE
})
//second JSON request
.then(function(){
$.getJSON(userURL).done(function(index){
userWeather = index;
console.log(userWeather);//THIS RETURNS LAST, WORKS FINE BUT SHOULD RETURN SECOND
});
})
//do stuff here
.then(function(){
$("#locat").text(arrLocat.city + ", " + arrLocat.regionName + ", " + arrLocat.country);
console.log(userWeather);//THIS RETURNS BLANK GLOBAL VALUE, NOT CARRYING VALUE FROM SECOND .THEN FUNCTION ALSO SHOULD RETURN LAST NOT SECOND
})
});
我正在尝试按照它们编写的顺序运行它们,我知道 getJSON 是异步的,但我认为 .then() 是为了强制顺序,等待前一个完成后再执行。
我花了很长时间才弄清楚发生了什么,似乎我的最后一个 .then() 在第二个 .then() JSON 请求之前运行。 我是延迟对象的新手,所以我可能正在做一些我不知道的根本错误?
【问题讨论】:
标签: javascript jquery json ajax jquery-deferred