How to convert an Ajax call to a Promise
Gishan Chaminga Abeysinghe
Posted on November 11, 2021
As you know $.ajax is the most famous way to do an ajax call to any api, but sometimes you might need to convert this callback based ajax call to promise based. Actually using this method you can convert any callback to a promise.
function ajaxPromise(data, url, type) {
return new Promise(function (resolve, reject) {
$.ajax({
type,
url,
data,
success: function (response) {
resolve(response);
},
error: function (error) {
reject(error);
},
});
});
}
What are the real benefits of this method
- Now you can use this inside an try catch block with async await.
- You can call your ajax calls in a for loop.
- Avoid callback hell.
try {
for (let index = 0; index < ajaxCalls.length; index++) {
const { url, data,type } = ajaxCalls[index];
res = await ajaxPromise(data, url, type);
}
} catch (error) {
console.log(error);
}
I hope this article is useful for you.
💖 💪 🙅 🚩
Gishan Chaminga Abeysinghe
Posted on November 11, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.