How to Promisify an Ajax Call?

Ajax Call – If you write JavaScript code, you will need to deal with asynchronous actions at some time. Consider an HTTP request to a Web service, for example. Although HTTP requests may be process synchronously, your application will run faster if you embrace asynchronous actions completely. With browsers allowing more concurrent activities, it’s more critical than ever to make use of numerous simultaneous requests.

By asynchronous, I mean that a request is made, and that request is finally completed at a later time. The secret is to specify the code that will be execute after the request is complete. A callback function is use to do this.

The good news is that you won’t have to start from scratch when using the Promise Pattern. The Promise Pattern is completely bake into the jQuery Ajax function, and this article will use that implementation.

Assume you have an AJAX call and another function that relies on the AJAX call loading before it can execute.

The AJAX function is seen below.

function doTheThing() {
  $.ajax({
    url: window.location.href,
    type: 'POST',
    data: {
      key: 'value',
    },
    success: function (data) {
      console.log(data)
    },
    error: function (error) {
      console.log(error)
    },
  })
}

And you may call the two functions one after the other, only to discover that the second one doesn’t work since it relies on the first.

doTheThing()
doSomethingElse()

With a Promise, we can quickly and simply rewrite this.

function doTheThing() {
  return new Promise((resolve, reject) => {
  $.ajax({
    url: window.location.href,
    type: 'POST',
    data: {
      key: 'value',
    },
    success: function (data) {
      resolve(data)
    },
    error: function (error) {
      reject(error)
    },
   })
  })
}

Now we can make the AJAX call, execute the success function, and continue with the rest of the code.

doTheThing()
  .then((data) => {
    console.log(data)
    doSomethingElse()
  })
  .catch((error) => {
    console.log(error)
  })

Conclusion – Ajax Call

When you don’t know the tools and strategies available to make your efforts simpler, programming in an asynchronous environment can be demanding and complex. Asynchronous programming is a must-have skill in JavaScript, and the Promise Pattern is the best solution to deal with asynchronous difficulties as quickly and painlessly as possible. You studied how promises are implemented in JavaScript under jQuery in this post.

If you have any queries regarding this article comment below and also visit Softhunt.net for more Updates

Leave a Comment