您好,我有兩個JSON請求作出天氣項目,我需要來自第一個請求的數據,以便爲用戶個性化第二個請求。我的第一個請求獲取用戶的緯度和經度,第二個請求需要這些地點當前天氣的url中的這些座標。運行按時間順序同步的getJSON請求
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()JSON請求之前運行。 我是新來的延期對象,所以我可能會做一些根本性錯誤,我不知道?
謝謝!我不知道我到底在做什麼,但是你提供的結構有很大的幫助,我想我現在更瞭解Promises。 – Doodles