0

Jquery version: 3.6.2

When writing an ajax request I want to avoid callback functions like .done() due to readability. I wish to only use var result = await $.ajax({}); . Creating a complete promise is also not what I'm looking for since this is even less readable than the callbacks. Normally I can easily do the following to get the result of the request:

async function GetThing(){
    var result = await $.ajax({
        type: "GET",
        url: "/PathToBackEnd"
    });
}

This function returns the exact value I expect. Recently a requirement to get the XHR object has arose to access some headers from the response. Is there a way this can be achieved and still avoid the callback functions? I'm looking for easily readable code so if the resulting code becomes highly complicated/unreadable I'd rather implement the callbacks.

I have not been able to find much information about this implementation. I find it to be way more readable and wish to keep implementing this pattern. Since I can't find much about this it kind of worries me that it is not meant to be used in this manner.

This is the current implementation (with callbacks):

$.ajax({
    type: "POST",
    url: "/path",
    //extra settings
}).done(function(response, status, xhr) {
    var header = xhr.getResponseHeader("TheHeader");
    //code
})
0

1 Answer 1

2

I wish to only use var result = await $.ajax({});

Split it into two steps. You don't want only the result, you also want the awaitable object itself. For example:

var response = $.ajax({});
var result = await response;
var header = response.getResponseHeader("TheHeader");

After having awaited the response, that fulfilled awaitable object then contains the other XHR data you're looking for.

1
  • Thanks so much, i thought await would alter/dispose the response variable. I will try to implement this and mark as accepted when it works.
    – Roe
    Commented Jul 1 at 6:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.