DEV Community

Cover image for How to convert an Ajax call to a Promise
Gishan Chaminga Abeysinghe
Gishan Chaminga Abeysinghe

Posted on

5 3

How to convert an Ajax call to a Promise

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);
          },
        });
    });
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

I hope this article is useful for you.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (1)

Collapse
 
rohanvilloth profile image
Rohan Villoth ā€¢

Thanks! This helped me fix the async/await hell on my project. šŸ˜ƒ

šŸ‘‹ Kindness is contagious

Please leave a ā¤ļø or a friendly comment on this post if you found it helpful!

Okay