Codemunkie
Codemunkie

Reputation: 445

Attach deferred handlers to nested AJAX call outside function

I'm trying to create an AJAX method extension called getApi that will automatically add my bearer token to the request header.

I have a deferred function called getToken() that returns either the token from sessionStorage or from an endpoint if it has expired.

My extension method looks like this:

$.getApi = function (options) {
    getToken()
        .done(function (token) {
            options.headers = {
                Authorization: token
            };

            $.get(options);
        });
};

And I want to be able to attach a done() handler to the internal get request, like this:

$.getApi({
    url: "my endpoint" // Returns json
})
    .done(function (data) {
        // Do stuff with the json data
    });

How can I alter my getApi extension method to be able to attach handlers to the internal get request? Is there a better way to achieve what I am trying to do?

Upvotes: 0

Views: 31

Answers (1)

trincot
trincot

Reputation: 350137

Use the promise interface (then). Also return $.get() so you extend the promise chain:

$.getApi = function (options) {
    return getToken().then(function (token) {
 // ^^^^^^            ^^^^  
        options.headers = {
            Authorization: token
        };
        return $.get(options);
 //     ^^^^^^
    });
};

$.getApi({
    url: "my endpoint"
}).then(function (data) {
// ^^^^
    // ...etc
});

NB: There is no good reason to define getApi on the jQuery object. I would advise to just make it a global function: getApi.

Upvotes: 1

Related Questions