2015-11-02 25 views
0

我遇到了ajax/promise的问题。我总共有两个ajax请求,第二个ajax调用依赖数据由第一个ajax调用返回。如何用承诺链接两个ajax请求

我的第一个ajax调用查找#search的纬度,经度和国家代码。 我的第二个ajax调用查找该城市的天气,但API URL取决于我的第一个ajax调用返回的纬度,经度和国家代码。所以第二个Ajax调用在第一个Ajax调用完成之前无法启动。

我的逻辑在于var ajax1被分配了一个promise,而var ajax2在ajax1.then()检查ajax1的promise被解析后启动。然后ajax2运行并返回另一个承诺。最后,ajax2.done在检查ajax2的承诺解决后启动,然后启动我的successWeatherFunction()。

我的问题是,ajax2.done不能正常工作,因为console.log(“test”)没有显示在控制台上。两个较早的console.logs,console.log(info)和console.log(weatherApiUrl)正在工作。

谢谢!

$("#search").keypress(function(event) { 
if (event.which === 13) { 
    var searchCity = $("#search").val(); 
    var jsonURL = "http://autocomplete.wunderground.com/aq?query=" + searchCity + "&cb=?" 
    var ajax1 = $.getJSON(jsonURL); 
    var ajax2 = ajax1.then(function(data) { 
    var info = []; 
    info.push(data["RESULTS"][0]["name"]); 
    info.push(data["RESULTS"][0]["c"]); 
    info.push(data["RESULTS"][0]["lat"]); 
    info.push(data["RESULTS"][0]["lon"]); 
    console.log(info); 
    var searchLat = info[2]; 
    var searchLng = info[3]; 
    var countryCode = info[1]; 
    if (countryCode === "US") { 
     var weatherApiUrl = "https://api.forecast.io/forecast/{APIKEY}/" + searchLat + "," + searchLng + "?exclude=minutely" + "&callback=?"; 
    } else { 
     var weatherApiUrl = "https://api.forecast.io/forecast/{APIKEY}/" + searchLat + "," + searchLng + "?exclude=minutely" + "?units=si" + "&callback=?"; 
     console.log(weatherApiUrl); 
    } 
    return $.getJSON(weatherApiUrl); 
    }); 
    ajax2.done(function(data){ 
    console.log("test"); 
    successCityWeather(data); 
    }); 
+1

添加一些错误检查...'ajax2.catch(函数(ERR){执行console.log(ERR);})有(......你做功能...);' –

+0

http://jsfiddle.net/arunpjohny/pkbfn5bt/1/ –

+0

just sayin,''?exclude = minutely“+”?units = si“'对我来说看起来像一个无效的URL部分 – Bergi

回答

1

代码中使用thendonedone是旧承诺的jQuery语法,因此您应该只使用then

下面的代码对我的作品:

$(function() { 
    $.get('/test').then(function() { 
    console.log('First request end'); 
    return $.get('/test'); 
    }).then(function() { 
    console.log('second request end'); 
    }); 
}); 

但在你的情况,也许你的请求的一个失败。给第二个参数来then记录错误:

$.getJSON('...').then(function(data) { 
    console.log('success', data); 
}, function(data) { 
    console.log('fail', data); 
}); 
0

如果不能确定,请始终使用always()处理程序。这样你就会知道请求是否真的完成了,或者根本没有完成。

$.ajax(...params...) 
     .always(function(jqXHR, textStatus) { 
      if (textStatus != "success") { 
        alert("Error: " + jqXHR.statusText); //error is always called .statusText 
      } else { 
        alert("Success: " + jqXHR.response); //might not always be named .response 
      }}); 
0
$.post(jsonURL) 
    .then(function (data) { 
     var info = []; 
     // some actions 
     return $.getJSON(weatherApiUrl); 
    }) 
    .then(function(data, status, promise) { 
     // some actions 
     successCityWeather(data); 
    }) 
+3

OPs代码有什么区别,为什么这很重要?请为您的答案添加解释。 – Bergi