score:0

You need to create a function which handles that you have a proper request sender. This is a promisified request sender:

function makeRequest (method, url, succ, err) {
  return new Promise(function (resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.onload = function () {
      if (this.status >= 200 && this.status < 300) {
        resolve(xhr.response);
        succ(response);
      } else {
        reject({
          status: this.status,
          statusText: xhr.statusText
        });
        err(response);
      }
    };
    xhr.onerror = function () {
      reject({
        status: this.status,
        statusText: xhr.statusText
      });
      err(xhr.statusText);
    };
    xhr.send();
  });
}

// Example:

makeRequest('GET', 'http://example.com')
.then(function (datums) {
  console.log(datums);
})
.catch(function (err) {
  console.error('Augh, there was an error!', err.statusText);
});

Source: How do I promisify native XHR?

Now, let's create a function which awaits that promise:

async function syncedRequest(method, url, succ, err) {
    await makeRequest(method, url, succ, err);
}

Implement success and error callbacks:

function successTokenCallback(response) {
    this.token = response;
}

function errorTokenCallback(message) {
    console.log(message);
}

and a token refresher:

function refreshToken(value) {
    syncedRequest(method, url, successTokenCallback, errorTokenCallback);
    //do something with successTokenCallback.token
    return value;
}

and you can do this wherever you want a token refresh to happen before the return:

return refreshToken(value);

The problem I see with this is that you are making your requests synchronous, which is in general an anti-pattern. You should aim to avoid blocking your Javascript flow because you wait for a request whenever possible. However, if it is absolutely necessary, you can do the above.


Related Query

More Query from same tag