What is the best way to store the outcome of a promise in a variable within a TypeScript constructor?

Is it possible to store the result of a promise in a variable within the constructor using Typescript?

I'm working with AdonisJS to retrieve data from the database, but the process involves using promises. How do I assign the result to a variable?

The variable needs to be accessible within the constructor.

Below is the code:


private teste1: any
private teste2: any

constructor(protected ctx: HttpContextContract) {

   Database.from('estoquepas').then(res => {
     this.teste1 = res;
     console.log(res)
   })

   Estoquepas.findBy('siagreId', this.IDSiagre.siagreId).then(res => {
      this.teste2 = res;
      console.log(res)
   })
   
   console.log(this.teste1)
   console.log(this.teste2)
}

Even though the console displays the values, the variables `teste1` and `teste2` remain undefined. Any assistance on resolving this issue would be greatly appreciated. Thank you for your help in advance.

Answer №1

In order to achieve this, you can implement a static asynchronous method in your class along with a basic constructor that only assigns values provided to it (once the async function has completed its tasks):

class Something {
    constructor (
        protected ctx: HttpContextContract,
        private teste1: any,
        private teste2: any
    ) { }

    static async create (ctx: HttpContextContract) {
        const [ teste1, teste2 ] = await Promise.all[ Database.from('estoquepas'), Estoquepas.findBy('siagreId', IDSiagre.siagreId) ]

        return new this(ctx, teste1, teste2)
    }
}

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

Issue with Vue.js where the v-if directive placed inside a v-for loop does not properly update when

I want to dynamically show elements from an array based on boolean values. However, I am facing an issue where the element does not disappear even after the boolean value changes. <li v-for="(value, index) in list"> <span> {{ value[0] }} & ...

Is there a way to utilize JavaScript in order to trigger a CSS animation to occur at a designated time during a video

I have a cool animated image element that I want to play at a specific point in time during a video using JavaScript. I'm not sure how to make it happen, but I know the .currentTime property could be the key. My goal is for the animation to only play ...

How can I load data into Vuex store before the application starts?

Within the created hook of App.vue, I am initiating a dispatch call to my store. Subsequently, in a child component, I attempt to retrieve this data using a getter. However, an issue arises as the child component is loaded before the data is stored, causin ...

Unable to arrange an array of JavaScript objects retrieved via an Angular REST request

I'm currently encountering an unusual issue with sorting an array of JavaScript objects. While sorting some dummy data works fine, I am unable to sort the array when fetching the object through an Angular REST call. The structure of the message is as ...

Having trouble executing a jQuery function within AJAX-generated code

I may not be very experienced in JavaScript programming, but I am learning and trying my best to improve. Please excuse any errors I make along the way. Currently, I am attempting to use Ajax (not jQuery ajax) to save customer details, which then returns ...

The error page is requesting a root-layout, which indicates that having multiple root layouts is not feasible

My issue is as follows: The not-found page located in my app directory requires a root-layout which I have added to the same directory. However, this setup prevents me from using multiple root layouts in the structure below. How can I resolve this? It see ...

Guide on how to navigate to a different page upon logging in with react-router-dom V5

I have implemented routing in my create-react-app using react-router-dom version 5.2.0. My goal is to use react-router for redirects and route protection within the application. The initial landing page is located at /, which includes the login/signup fun ...

Let the Vuejs transition occur exclusively during the opening of a slide

Trying to implement a smooth transition when the toggle button is clicked. Successfully applied the transition effect on the slider, but struggling to animate the text inside the div.hello class upon sliding open. <transition name="slide"> <a ...

Encountering a ReferenceError stating that the window object is not defined while building a React Leaflet application

In my upcoming nextjs project, I've incorporated react-leaflet. It behaves flawlessly in dev mode. However, upon attempting to build the project, it throws a ReferenceError: window is not defined. Despite setting ssr to false in dynamic, the error per ...

Showing the date in AngularJSAngularJS can be used to

I have a view set up in AngularJS and I'm attempting to show the current date in a formatted way. My initial thought was to use <span>{{Date.now() | date:'yyyy-MM-dd'}}</span> to display the current date. ...

Issues with collision detection between circles within grouped clusters

I am currently developing a game with circle-shaped gameobjects, similar to agar.io. I have implemented a collision system for these objects, which works well most of the time. However, when there are more than two objects in close proximity, the game beco ...

The filter functionality is not functioning properly in AngularJS

Currently, I am working on an AngularJS extension and encountering an issue with the filter functionality. In the popup page of my extension, there is a button. Upon clicking this button, the ancestor node of the button gets blocked, and its relevant info ...

How to upload multiple files using AngularJS and Laravel without using a form tag

I am seeking a solution to upload multiple files without using the form tag, utilizing AngularJS with Laravel 5.2. The code snippet below is functional for uploading a single file but fails when attempting to upload multiple files. Here is the HTML Code: ...

Router-view failing to display component

I am currently working on setting up basic routing in Vue. I have identified three file listings that seem to be causing issues. When I include <router-view> in app.vue, the foo component appears in the browser. However, when I follow the instruction ...

Hide all the div elements on the web page and only display one when a button is clicked

I have successfully set up a few buttons that can show and hide divs on click. However, I am wondering if it is possible to hide all other divs when one is showing, and also have "divone" show up on load. Buttons: <button class="btn btn-outline-primar ...

Angular 2: Enhancing Textareas with Emoji Insertion

I am looking to incorporate emojis into my text messages. <textarea class="msgarea" * [(ngModel)]="msg" name="message-to-send" id="message-to-send" placeholder="Type your message" rows="3"></textarea> After entering the text, I want the emoj ...

The transformation from className to class attribute does not occur for custom elements in JSX

I recently encountered an issue with one of my React components where the "className" attribute was being converted to "classname" in the resulting HTML, instead of the expected "class" attribute. The component had a custom element definition as follows: ...

After each animation in the sequence is completed, CSS3 looping occurs

I have currently set up a sequence of 5 frames, where each frame consists of 3 animations that gradually fade into the next frame over time. My challenge is figuring out how to loop the animation after completing the last sequence (in this case, #frame2). ...

Issue with Jquery UI sortables not functioning properly

Struggling with getting a sortable list to work using jQuery UI. The ul element is receiving the class 'ui-sortable' but nothing seems to be happening. To demonstrate this issue, I created an example since the original javascript code is quite c ...

There seems to be a problem with the Chart property getter as it

I'm in the process of creating an object that corresponds to chartJS's line-chart model <line-chart :data="{'2017-05-13': 2, '2017-05-14': 5}"></line-chart> There is an API I utilize which returns a standard arra ...