AJAX
Basics
Data
DOM
Effects
Events
Forms
jQuery UI
Plug Ins
Traversing
https://petetasker.com/using-async-await-jquerys-ajax
Imagine you needed to make a series of jquery ajax
calls - each one dependent on the previous one.
In this scenario, we want to get just the first Point Of Interest from the first City in a collection of Cities.
For whatever imaginary reason, this needs to be 3 separate calls. We do not immediately know the city's
id
or the Point of Interest's id
.
The order of operations and three calls would be:
Each step must await
the results of the previous.
async function StartCalls()
{
// get all the cities...and use the first one
let cities = await GetAllCities(1, 10);
// get the city with its points of interest
let city = await GetCityWithPointsOfInterest(cities[0].cityId);
// get the point of interest
let pointOfInterest = await GetFirstPointOfInterest(city.cityId, city.pointsOfInterest[0].pointId);
let html = `cityId: ${pointOfInterest.cityId}<br />`;
html += `pointId: ${pointOfInterest.pointId}<br />`;
html += `description: ${pointOfInterest.description}`;
$("#demo-content").html(html);
$("#demo-container").removeClass("d-none");
$("#code-container").removeClass("d-none");
}
async function GetAllCities(pageNum, pageSize)
{
const ajaxGetSettings =
{
url: `https://city-info-api-prod.azurewebsites.net/api/v1.0/cities?pagenumber=${pageNum}&pagesize=${pageSize}`,
type: "GET"
};
// thorough version
let apiResults = await $.ajax(ajaxGetSettings)
.done(function (response, statusTxt, xhr)
{
// your done code here
// if (xhr.status === 200)...etc
console.dir(xhr.status);
console.dir(xhr.statusText);
})
.fail(function (xhr, statusTxt, errorThrown)
{
// your fail code here
console.error(`Error: ${errorThrown}`);
})
.always(() =>
{
// always is executed
//console.log("GetAllCities called.");
});
return apiResults;
}
async function GetCityWithPointsOfInterest(cityId)
{
const ajaxGetSettings =
{
url: `https://city-info-api-prod.azurewebsites.net/api/v1.0/cities/${cityId}?includePointsOfInterest=true`,
type: "GET"
};
let apiResults = await $.ajax(ajaxGetSettings);
return apiResults;
}
async function GetFirstPointOfInterest(cityId, pointId)
{
const ajaxGetSettings =
{
url: `https://city-info-api-prod.azurewebsites.net/api/v1.0/cities/${cityId}/pointsofinterest/${pointId}`,
type: "GET"
};
let apiResults = await $.ajax(ajaxGetSettings);
return apiResults;
}