How to get data, textStatus and jqXHR when calling await jquery.ajax?

Viewed 278

I am using JQuery AJAX, using await. I do not want to use the success and error callbacks and I do not want to use the .then syntax.

When calling jquery ajax like so

const { data, textStatus, jqXHR } = await $.ajax(url, {...});

then the variables on the left are not populated.

How to call jquery ajax using await and still get data, textStatus and jqXHR (similar to the success callback)?

(Simply calling const data = await $.ajax(url, {...}); works but I need access to textStatusand jqXHR.)

2 Answers

you can get the 3 parameters you specified in the success option for the ajax function and do the destructuring on that anonymous function

    let data, textStatus, jqXHR;
    await $.ajax(url, {success: (dt, txt, jqx) => {
      data = dt;
      textStatus = txt;
      jqXHR = jqx;
    }});

or extract the function and do it like this

...
const success = (dt, txt, jqx) => {
  data = dt;
  textStatus = txt;
  jqXHR = jqx;
}
...
await $.ajax(url, {success});
...

Based of the jQuery documentation (as i haven't used jQuery in many years), it seems that $.ajax returns jqXHR so one approach could be not to use await on the jqXHR object when you call await $.ajax(...) you could do something like the following instead

  const jqXHR = $.ajax("https://jsonplaceholder.typicode.com/todos/1");
  const data = await jqXHR;
  const statusText = jqXHR.statusText;

  console.log({ data, statusText, jqXHR });

or if you like it as a in your example you could write a small wrapper function, or maybe it is possible to achieve with the $.ajaxSetup as well

an example of a wrapper function could be something like

async function ajax() { 
   return new Promise((resolve, reject) => {
     $.ajax(...arguments)
      .then((data, statusText, jqXHR) => resolve({ data, statusText, jqXHR }))
 })
}

and you can then use ajax instead of $.ajax like

const { data, statusText, jqXHR } = await ajax("https://jsonplaceholder.typicode.com/todos/1");
Related