2017-02-11 64 views
0

您好,我有兩個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請求之前運行。 我是新來的延期對象,所以我可能會做一些根本性錯誤,我不知道?

回答

0

一,不請使用.done(),僅限使用.then().done()是非標準的,並有一些奇怪的行爲。標準爲.then()。第二,當您在.then()中有第二個承諾時,您需要將其從.then()處理程序中返回以正確鏈接它。

在結構上,你希望它看起來是這樣的:

$.getJSON(...).then(function(result1) { 
    return $.getJSON(...) 
}).then(function(result2) { 
    // do stuff here 
}); 

而且,請注意,這裏需要在所有以得到最終結果到最後.then()處理NO全局。你也可能會發現這個有用:

How to chain and share prior results with Promises

+0

謝謝!我不知道我到底在做什麼,但是你提供的結構有很大的幫助,我想我現在更瞭解Promises。 – Doodles

-1

鏈在一起的自稱對方內線,沒有必要使用。那麼(),這是一個承諾,不是所有的API的實現這種方式的一部分...

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); 
    $.getJSON(userURL).done(function(index){ 
     userWeather = index; 
     console.log(userWeather);//THIS RETURNS LAST, WORKS FINE BUT SHOULD RETURN SECOND 
     $("#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 
    }); 
    }); 
}); 
+0

承諾是比普通的回調,尤其是管理異步操作一個更強大的方案,當談到測序和傳播錯誤或協調多個異步操作。 – jfriend00

+0

感謝您的幫助,代碼工作絕對,但與承諾一起工作是一個更好的學習經驗,爲新手 – Doodles