如何使用promises链接两个ajax请求

时间:2015-11-02 08:04:27

标签: javascript jquery ajax promise

我遇到了ajax / promises的问题。我总共有两个ajax请求,第二个ajax调用依赖于第一个ajax调用返回的数据。

我的第一个ajax调用找到了#search值的纬度,经度和国家/地区代码。 我的第二个ajax调用找到了该城市的天气,但API URL取决于我的第一个ajax调用返回的纬度,经度和国家/地区代码。因此,第二个ajax调用无法启动,直到第一个完成。

我的逻辑是var ajax1被赋予一个promise,而var ajax2在ajax1.then()检查ajax1的promise被解析之后开始。然后ajax2运行并返回另一个promise。最后ajax2.done在检查ajax2的promise被解析后开始,然后启动我的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);
  });

3 个答案:

答案 0 :(得分:1)

您的代码使用thendonedone是旧的promises 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);
});

答案 1 :(得分: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
            }});

答案 2 :(得分:0)

$.post(jsonURL)
    .then(function (data) {
        var info = [];
        // some actions
        return $.getJSON(weatherApiUrl);
    })
    .then(function(data, status, promise) {
        // some actions
        successCityWeather(data);
    })
相关问题