【发布时间】:2016-08-19 02:02:44
【问题描述】:
在构建将根据用户的位置坐标提供天气数据的应用程序时,我开发了以下代码(也可在此代码笔http://codepen.io/PiotrBerebecki/pen/QNVEbP 中找到)。
用户的位置将由getCoordinatesMethod1() 函数传递。但是,如果此操作失败,则应通过 getCoordinatesMethod2() 函数传递位置。
如何将getCoordinatesMethod2() 添加到promise 链(在底部),以便仅在getCoordinatesMethod1() 未能提供位置时使用?
此外,将来为了使应用程序更健壮,我可能会添加更多方法来获取位置数据,因此链逻辑也应该能够适应这种情况。
// The first method to get user location coordinates.
function getCoordinatesMethod1() {
return $.ajax('http://wwww.example.com/coordinates-method-1.json');
}
// The second method to get user location coordinates.
// This should only be used if method 1 fails to deliver coordinates.
function getCoordinatesMethod2() {
return $.ajax('http://wwww.example.com/coordinates-method-2.json');
}
// Function which provides weather data depending on user coordinates.
function getCurrentWeather(latitude, longitude) {
return $.ajax('http://www.example.com/lat=' + latitude + '&lon=' + longitude + 'weather.json');
}
// Promises chain
getUserCoordinates1().then(function(locationData) {
return getCurrentWeather(locationData);
}).then(function(weatherData) {
return showCurrentWeather(weatherData);
})
【问题讨论】:
-
你使用的是 jQuery 3 还是早期版本的 promises?
-
目前我使用的是 jQuery 2.2.2。
标签: javascript jquery ajax asynchronous promise