How to Promisify an Ajax Call

Let's say you have an AJAX call, and some other function that depends on the AJAX call loading before it runs.

Here's the AJAX function.

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 might call the two functions in succession, and find that the second function doesn't work, because it depends on the first one.

doTheThing()
doSomethingElse()

We can quickly and easily rewrite this with a Promise

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 do the AJAX call, run the success function, and follow it up with any subsequent code.

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

And that's it!

Leave a comment

Plain text only. Comment must be over 20 characters.

Join the newsletter

I write about JavaScript, programming, and front-end design. Join other developers in keeping up with my content. Unsubscribe whenever. Never any spam, ads, or affiliate links.