Tips for patiently waiting for an axios request to finish

Within my vuejs application, I am faced with the challenge of initializing an object using data retrieved from an ajax call:

let settings = {}
api.readConfig().then((config) => {
  settings = {
    userStore: new Oidc.WebStorageStateStore(),
    authority: config.data.urls.auth,
    client_id: config.data.clientid,
    redirect_uri: `${window.location.protocol}//${window.location.hostname}${window.location.port ? `:${window.location.port}` : ''}${process.env.ROUTER_BASE}static/callback.html`,
    response_type: 'id_token token',
    post_logout_redirect_uri: config.data.urls.auth,
  }
})

const authMgr = new Oidc.UserManager(settings)
export default authMgr

Upon exporting the object, all settings are null due to the asynchronous nature of the call.

I am seeking a solution on how to properly wait for the call to finish before exporting my constant.

Answer №1

Don't delay the export operation, instead utilize a method like this to create a promise chain. By doing so, you can delegate the task of resolving the promise to the callee module.

export default api.readConfig().then((config) => {
  return {
    userStore: new Oidc.WebStorageStateStore(),
    authority: config.data.urls.auth,
    client_id: config.data.clientid,
    redirect_uri: `${window.location.protocol}//${window.location.hostname}${window.location.port ? `:${window.location.port}` : ''}${process.env.ROUTER_BASE}static/callback.html`,
    response_type: 'id_token token',
    post_logout_redirect_uri: config.data.urls.auth,
  }
}).then((settings) => {
  return new Oidc.UserManager(settings);
})

In your callee module, you can implement something similar to this.

var config = require('./config');
config().then((userManager) => {
   ...
})

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

What is the best way to target an HTML attribute using jQuery?

I have customized a Textbox by adding a special attribute: <asp.TextBox MyCustomAttribute="SomeValue"><asp.TextBox> Now, I want to retrieve this value from within an AJAX success function. Please note that I have excluded irrelevant attribut ...

Is it possible to compile a .ts file at the root level without following the tsconfig.json configurations?

After dealing with the challenge of having both .ts and .js files coexisting in each folder for months, I have finally managed to get the app to compile correctly. The transition from JS to TS brought about this inconvenience, but the overall benefits make ...

Iterating through an array with conditional statements

I am currently considering the best approach to loop through an array in my code before proceeding further. I have some concerns about the link (var link = ... ) and the if statement. Is this the most optimal way to iterate over array1 and compare the val ...

Ajax - unauthorized invocation issue

I am currently working with the following function: function createSkillCard(attributeData,name) { $.ajax({ type: "POST", url: "/Skillcard/create", dataType: 'json', data: { request: 'aja ...

Utilizing Vue to send information to the POST function

I am encountering an issue with passing data to the Vue.js post method. I am using vue-resource and according to the documentation, it should be structured like this: this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCall ...

Typescript headaches: Conflicting property types with restrictions

Currently, I am in the process of familiarizing myself with Typescript through its application in a validation library that I am constructing. types.ts export type Value = string | boolean | number | null | undefined; export type ExceptionResult = { _ ...

Utilizing AJAX in Datatables- Effortlessly sharing a URL link to a designated page

I've recently encountered an issue while using Datatables and AJAX to retrieve data from my Rails server. The problem arises when I try to share a specific page (let's say page 2) with another user who is also using Datatables. Due to the paginat ...

Having trouble with GSAP CDN not functioning properly in your JavaScript or HTML document?

After watching a tutorial on YouTube by Gary Simon, I attempted to animate text using GSAP. Despite following the instructions meticulously and copying the CDN for GSAP and CSSRulePlugin just like him, nothing seems to be happening. Even setting my border ...

Execute the "organizeImports" trigger through the terminal in TypeScript

One feature of VSCode is its editor capability to organize and clean imports in javascript and typescript files upon saving ( "source.organizeImports": true ). Inquiry Is there a way to trigger this action on a file using the command line? Something alo ...

Guide on properly documenting custom function types in JSDoc or TypeScript to ensure accurate referencing for VSCode IntelliSense functionality

I am currently working on documenting custom function types within an object and would greatly appreciate any assistance: A Closer Look at the Issue Consider this basic object declaration with several function properties (addCoordinate, addCoordinateOne, ...

Using Vue 3's emit in place of v-model

I am facing a challenge with integrating a custom dropdown select component. The idea is to use v-model to retrieve data from the parent component, but I am unsure how to pass that through an emit. Can anyone clarify this for me? Here is my parent compone ...

What is the best way to open just a single detail in a b-table?

When the button is clicked, the row details are opened. To ensure that only one line detail remains open at a time, I want any previously open details to be closed when another one is opened. view sample screenshot If you look at the example provided, mu ...

Instructions for incorporating a personalized document in NextJs version 13

In order to enhance the design of my upcoming Next.js 13 project, I am looking to integrate a custom design system package. This particular package necessitates the creation of custom documents within the page directory, as outlined in the official Next. ...

What is the best way to prevent useEffect from triggering when a modal is being rendered?

I'm currently developing a react movie application. I am facing an issue with the hero picture feature that displays a random popular movie or show. Whenever I click the button to open a modal, the useEffect function is triggered and changes the movie ...

PHP-generated interactive pie chart

I'm encountering a puzzling issue while attempting to create a pie chart in Flot using data from PHP. The chart seems to be rendering incorrectly, and I'm struggling to identify the cause. Below is my PHP code (used for testing): echo json_enc ...

What is the best way to manage classNames dynamically in React with Material-UI?

I am wondering how to dynamically add and remove classes from an img tag. My goal is to change the image automatically every 2 seconds, similar to Instagram's signup page. I am struggling to achieve this using the material-ui approach. Below is a snip ...

Can a value of a variable be "stored" in NodeJS?

I am working on a website that allows clients to make their site go live by setting var live = true;. Once this variable is set, certain webpages will display. I would prefer not to store the live variable in a database as creating a collection solely fo ...

Transfer data from distinct arrays to separate variables

I have 2 arrays structured like this: let dataA = [{"id": "a1", "name": "Alpha"}, {"id": "a2", "name": "Beta"}, {"id": "a3", "name": "Gamma&quo ...

Cover any HTML element with a translucent overlay box

I have a unique problem with an HTML file that is out of my control when it comes to its content. My only option is to inject a CSS file and/or JavaScript (potentially using libraries like jQuery) into the mix. Within this HTML, there are elements that re ...

Are there any methods available to adjust the size of a View component in react-native?

My react-native application includes a View that contains several components. The layout displays perfectly on iPhone 6 and 5 models, but on an iPhone 4s, the bottom of one component is being clipped slightly. I'm aware of scaling base64 icons, but I ...