Tips for pausing execution until an asynchronous callback is finished?

Here are two methods that I have in my code.

The issue I'm facing is with the `get` method which I am overriding from the Http module. The problem is that the authentication success callback is being triggered after the request has already been executed and a response has been returned. This results in the JWT token being added to the headers in the incorrect order and at the wrong time.

I don't have a deep understanding of promises and observables, so I'm unsure how to make it wait for the callback to finish before proceeding with executing the request and sending back the response.

authenticate(authCompletedCallback, errorCallback) {
  let authContext = new Microsoft.ADAL.AuthenticationContext(AUTHORITY_URL);

  authContext.tokenCache.readItems().then((items) => {
    if (items.length > 0) {
        AUTHORITY_URL = items[0].authority;
        authContext = new Microsoft.ADAL.AuthenticationContext(AUTHORITY_URL);
    }

    // Attempt to authorize user silently.
    authContext
      .acquireTokenSilentAsync(RESOURCE_URL, CLIENT_ID)
      .then(authCompletedCallback, () => {
          // We require user credentials so trigger authentication dialog.
          authContext
            .acquireTokenAsync(RESOURCE_URL, CLIENT_ID, REDIRECT_URL)
            .then(authCompletedCallback, errorCallback);
      });
  });
}

get(url: string, options?: RequestOptionsArgs): Observable<Response> {
  this.authenticate((authResponse) => {
    // This section gets executed second.
    if (!options) {
      options = { headers: new Headers() };
    }

    options.headers.set('Authorization', 'Bearer ' + authResponse.accessToken);
  }, (err) => {
    alert(JSON.stringify(err));
  });

  // This part gets executed first.
  return super.get(url, options);
}

Answer №1

Consider redesigning your get function to return a promise, as the Response object should not be created until after authentication. It appears that you are overriding a method, so perhaps creating a separate method would be a better approach.

fetchWithAuthentication(url: string, options?: RequestOptionsArgs): Promise<Observable<Response>> {
 return new Promise((resolve, reject) => {
  this.authenticate((authResponse) => {
    if (!options) {
      options = { headers: new Headers() };
    }

    options.headers.set('Authorization', 'Bearer ' + authResponse.accessToken);
    let response = super.get(url, options);
    resolve(response);
  }, (err) => {
    alert(JSON.stringify(err));
    reject(err);
  });
 }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unlock the potential of displaying similar object values side by side in JavaScript, React, and ES6 - here's how!

Currently, I am dealing with an object called segregatedData which is being passed as props. Among its several properties, we are interested in segregatedData.type1. This particular property is essentially an array of strings similar to this: ['water& ...

Want to learn how to display a description below a photo when you hover over it in a photo gallery?

I am currently creating a basic photo gallery where hovering over a thumbnail displays an enlarged photo below it. My goal is to also have text displayed inside a white text box when hovering over each thumbnail, with unique descriptions for each. I need ...

Requesting title elements from an XML page using Ajax response is not functioning correctly

Could someone please help me understand why I am unable to retrieve the elements from an XML document? When I click on the et Title button in the body section, nothing is being displayed. Here's the code snippet: function MyF () { var xml ...

Extract a property from a JSON object

Is there a way to access the href properties and use them to create multiple img elements with their sources set as the extracted href properties? I'm looking for a solution in either javascript or jQuery. I attempted the following code, but it didn& ...

``motioning a component beneath another component that may be in a state

Having an issue with my CSS. I have some elements generated by JavaScript and when hovering over them, another element is displayed below the others for some reason. Here's the CSS related to this problem: .hiddenTextjob { display:none; ...

The age-old debate: Deciding between JavaScript's touchend and

Currently delving into some JavaScript UI work, focusing on optimizing touch events like 'touchend' for smoother interactions on touch-enabled devices. Nonetheless, encountering a few perplexing logical dilemmas... A common practice I've no ...

Utilizing a mathematical equation stored in JSON within a JavaScript environment

I'm in the process of creating a conversion calculator and I want to save the formulas and references in JSON format. Unfortunately, I'm uncertain on how to interpret the variable as a mathematical operation. JSON var JSON = { "conversio ...

Setting initial values for an object in JavaScript

I am currently seeking a method to store predefined values in a separate file for populating my function: Here is my function in index.js: const Modes = (array) => { return { name: array.name, funcionarioIncrease: array.funcio ...

Nested ng-repeats within ng-repeats

I have a question regarding the correct way to utilize an inner ng-repeat inside of an outer ng-repeat: Essentially, I am looking to implement something along these lines: <tr ng-repeat="milestone in order.milestones"> <td>{{mi ...

What could be causing my reducer function to return 'NaN'?

I have been working on updating the total quantity in my shopping cart. Utilizing hooks useSelector, I retrieve the state from Redux and access all the items currently in my cart. By using reduce function, I am able to calculate the total quantity of items ...

The replace function fails to recognize Cyrillic characters when combined with the /b flag

Struggling with a persistent issue, I've noticed that my code works perfectly with Latin characters but fails to recognize Cyrillic characters when using jQuery. $('p').each(function() { var $this = $(this); $this.html($this.text().re ...

You can use HTML tags within a script tag for added flexibility and

I'm working on incorporating this into a dynamic script using data from an XML file (aiming for 50% to be dynamic). <div class="progress-bar progress-bar-danger" data-progress-animation="50%" data-appear-animation-delay="20"> It currently func ...

Ensuring type safety for a generic union type

A new union type has been defined: type CustomParameterType = number | string | boolean | Array<number>; An object is created to hold key-value pairs of this union type: class CustomParameter { constructor(name: string, value: CustomParameter ...

Tips on toggling between slides with Bootstrap Carousel

I am in the process of designing a portfolio website and have encountered a challenge. I want to divide it into two sections - a brief introduction and a carousel for showcasing projects. While I have managed to set up both sections, I'm facing an iss ...

Utilizing TypeDoc to Directly Reference External Library Documentation

I am working on a TypeScript project and using TypeDoc to create documentation. There is an external library in my project that already has its documentation. I want to automatically link the reader to the documentation of this external library without man ...

Clicking on a radio button can trigger the selection of another radio button

I'm currently working on a form that includes 8 radio buttons - 4 for System A and 4 for System B. The options for the buttons are CF, ISO, ISO-B, and NW. My goal is to create a functionality where selecting a radio button in System A automatically se ...

Callback error in Ajax request

$(this).find(':submit').attr('disabled',true); $.ajax( { url:'/enviarSugerenciaMessageBoard', cache: false, type: 'POST', data: $(this).serialize(), ...

The Semantic UI dropdown consistently fails to return a value

I am currently utilizing Semantic UI for an ASP.NET core project, and I am encountering an issue when trying to submit a form that contains a drop-down element. Despite my efforts, it always returns null, and the lack of proper documentation on this matter ...

Is it possible to anticipate a particular word following a route parameter in Node.js?

My current route setup looks like this: router.get('/:board/:threadId', function(req, res, next) { // performing actions here }); When users visit /a/1, it triggers the route with board = a and threadId = 1. Now, I want users to have to vis ...

The combination of curly brackets and displaying items in a list

What is the reason behind React's failure to render the list items when the arrow function objectList contains curly braces? export default function StatelessList() { const objDev = [ { id: 1, surename: "John", name: "Wayne" ...