I am working on an ASP.NET Web Forms project where the front-end is developed using typescript and JQuery.
The current code makes sequential calls like this,
private SearchByID() {
$.when(DefaultComponent.Method5(), DefaultComponent.Method4())
.always(function () {
DefaultComponent.Method1();
}).always(function () {
DefaultComponent.Method3();
})
.always(function () {
DefaultComponent.Method2();
});
}
These method are depending on other method's response. Also, these methods can be invoked in any order based on the search type of the user. For example, if the user is searching by Name then,
private SearchByName() {
$.when(DefaultComponent.Method1(), DefaultComponent.Method2())
.always(function () {
DefaultComponent.Method5();
}).always(function () {
DefaultComponent.Method4();
})
.always(function () {
DefaultComponent.Method3();
});
}
Code inside the method will look like this,
private static Method1() {
let deferred = $.Deferred();
//data validation
//create and pass request object
let requestXhr = DefaultService.GetMethod1Data();
$.when(requestXhr).done(function (response: string) {
//handle response
$("#DivResult").append(response).append("<br />");
deferred.resolve();
}).fail(function () {
//display error
deferred.reject();
}).always(function () {
//display mossages based on respons in UI
});
return deferred.promise();
}
The above way is working now. However, I am trying to make it more readable and simple by using async await along with JQuery ajax.
I tried to following the async await example in typescript documentation but, not sure how to proceed.
Example from typescript document:
// Async/Await took code which looked like this:
// getResponse(url, (response) => {
// getResponse(response.url, (secondResponse) => {
// const responseData = secondResponse.data
// getResponse(responseData.url, (thirdResponse) => {
// ...
// })
// })
// })
// And let it become linear like:
// const response = await getResponse(url)
// const secondResponse = await getResponse(response.url)
// const responseData = secondResponse.data
// const thirdResponse = await getResponse(responseData.url)
// ...
// Which can make the code sit closer to left edge, and
// be read with a consistent rhythm.
Any suggestion /examples will be greatly appreciated.