Guy
Guy

Reputation: 13286

Javascript promises: how to deal with token expiry in API calls?

When I am receiving an error from my API that my token has expired I want to be able to re-issue a new token and repeat the request as first sent without the user feeling any difference. Is there a way to handle this use case elegantly?

function relogin(userInfo) {
    return Q.Promise(function (resolve, reject) {
        // ...
    });
}

function makeTransaction(token, options) {
    dataOperations.makeTransaction(token, options).then(function (result) {
        // notify ui - new data yey!
    }).catch(function (err) {
        if (err.code === 304) {
            relogin.then(function (token) {
                makeTransaction(token, options);
            }).catch(function (err) {
                // notify UI - problems with server
            });
        }
    });
} 

Upvotes: 1

Views: 229

Answers (1)

Dan O
Dan O

Reputation: 6090

that code looks pretty good already. what specifically is your issue? If you have many transactions and you're worried about code duplication, and checking for HTTP 304 many times, you could wrap your transactions in a handler:

function relogin(userInfo) {
  return Q.Promise(function(resolve, reject) {
    // ...
  });
}

function myTask(params) {
  return Q.Promise(function(resolve, reject) {
    // ...
  });
}

function doTask(fn, context, params) {
  return fn.apply(context, params).then(function(results) {
    return results;
  }).catch(function(err) {
    if (err.code === 304) {
      return relogin({}).then(doTask(fn, context, params));
    }
    else {
      return err;
    }
  });
}

// ...

$("#foo").on("click", function(e) {
  doTask(myTask, this, params).done(function(results) {
    alert("all done");
  }).catch(function(err) {
      alert(err);
  });
});

Upvotes: 1

Related Questions