I'm using the latest JQuery (3.6).There are multiple ajax call in my code to the same end point. I've to make duplicate methods because based on the response, in the .done function, I have to apply separate business logic and in case of error apply additional logic to show the error to the user. I'm wondering if I can reuse the same ajax call code because that doesn't change. Here is my JS functions:
js function 1
function dosomething1(req) {
var send_on = "/api/url";
var timeoutTime = 10000;
$.ajax({
type: "POST",
url: send_on,
contentType: 'application/json',
data: JSON.stringify(req),
cache: false,
dataType: "json",
tryCount: 0,
retryLimit: 1,
timeout: timeoutTime
})
.done(function(response) {
// this is where I'm doing my businses logic
do_very_specific1_to_response(response);
})
.fail(function(xhr, status, error) {
// this is where I'm doing error handling
handle_very_specific1_to_response();
}
js function 2
function dosomething2(req) {
var send_on = "/api/url";
var timeoutTime = 10000;
$.ajax({
type: "POST",
url: send_on,
contentType: 'application/json',
data: JSON.stringify(req),
cache: false,
dataType: "json",
tryCount: 0,
retryLimit: 1,
timeout: timeoutTime
})
.done(function(response) {
// this is where I'm doing my businses logic
do_very_specific2_to_response(response);
})
.fail(function(xhr, status, error) {
// this is where I'm doing error handling
handle_very_specific2_to_response();
}
As you can see, I am not chaning anything for ajax request and retry logic, that is always same, what changes is how I'm handling the response.
I was thinking to apply $.when().then() mechanism but not sure how it would handle the retry logic.
CodePudding user response:
One approach would be to wrap the ajax call in a promise.
function dosomething(req) {
return new Promise((resolve, reject) => {
var send_on = "/api/url";
var timeoutTime = 10000;
$.ajax({
type: "POST",
url: send_on,
contentType: 'application/json',
data: JSON.stringify(req),
cache: false,
dataType: "json",
tryCount: 0,
retryLimit: 1,
timeout: timeoutTime
})
.done(function(response) {
// this is where I'm doing my businses logic
resolve(response);
})
.fail(function(xhr, status, error) {
// this is where I'm doing error handling
reject(error);
})
}
function dosomething1(req) {
dosomething(req)
.then(response => {
do_very_specific1_to_response(response);
})
.catch(error => {
handle_very_specific1_to_response();
})
}
function dosomething2(req) {
dosomething(req)
.then(response => {
do_very_specific2_to_response(response);
})
.catch(error => {
handle_very_specific2_to_response();
})
}