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

Each time the button is clicked, the settings and values will rotate, creating a new

I'm looking to create a button system that transitions from "unmarked" to "form" and updates the database with each click. I want users to be able to cycle through the buttons, triggering a post request via ajax to update the associated ID in the data ...

Logging in using email, phone number, or username on Node.js platform

How can I implement a login system in node.js and MongoDB that allows users to log in with their email, phone number, or username along with a password? Similar to the login functionality seen on Instagram, users should be able to enter their email or u ...

Utilizing the principles of object orientation in Javascript to enhance event management

After attempting to modularize my JavaScript and make it object oriented, I found myself struggling when dealing with components that have multiple instances. This is an example of how my code currently looks: The HTML file structure is as follows: & ...

What is the best way to store JSON encoded items in an array using square brackets?

Currently, I am utilizing Javascript along with NodeJS to dynamically generate an array of JSON objects. My goal is to store this array of JSON objects in a .json file for future reference. However, when I attempt to save the file, I encounter an issue whe ...

When using AWS/Cognito and setting up a user pool with CDK, is there a way to specify the character limits for standard attributes? Specifically, I would like to establish a minimum and maximum

When setting up a user pool in AWS/Cognito using CDK, how can I specify the string length for standard attributes? I've been trying to figure this out but haven't had any luck so far. I'm working with Typescript. This is how my user pool i ...

Exploring the Power of JQuery with Hover Effects and SlideToggle

I was struggling to keep the navbar displaying without it continuously toggling when my pointer hovered over it. I just wanted it to stay visible until I moved my pointer away. <script> $(document).ready(function(){ $(".menu-trigger").hover(funct ...

When it comes to using the text() function, the statement encounters difficulty

let person = $(".tekst").text(); if (person=="XxX") { $("#discu").css("display", "none"); } alert(person); When I access my element with class .tekst and get its text using the text() function, it correctly displays as XxX, which is what I expected. ...

Is there a way to asynchronously load multiple textures in three.js using a callback function?

Bringing in a single texture with a callback is a simple task, for instance: var loader = new THREE.TextureLoader(); var texture1 = loader.load("https://i.imgur.com/UiTMJzv.png", process); //executed only once texture1 is loaded function process(){ } B ...

Unsuccessful attempts to animate with Jquery in Google Chrome are persisting

I've been facing a challenge with my jquery code that seems to be getting the "click" function but does not animate. Instead, it just abruptly jumps without any smooth animation. I've spent hours trying to troubleshoot this issue. Here is the Jq ...

Tips on resolving the issue of an Axios post request not appearing in a get request in React

When using axios to make a post request in this code, a new username is posted, but there is an issue with retrieving the posted name from the API. How can I fix this problem to view my posted request? const App = () => { const [data, setData] = u ...

Error message 'Object doesn't have support for this property or method' is triggered by a basic JSON object

Recently, I developed a compact framework for loading resources asynchronously (hyperlink). The framework functions properly in modern browsers such as Opera, Chrome, and Firefox. However, when testing it in IE8, the code fails to execute. Internet Explor ...

When a function inside React uses this.props, it won't trigger the corresponding function

I am currently developing a Checklist using React and MaterialUI that consists of two components. One component is responsible for managing the data, while the other component allows for editing the data. However, I have encountered an issue where the func ...

There seems to be an issue with the functionality of chrome.storage.local.set()

Struggling with Chrome storage handling, I have reviewed the newest documentation for Chrome storage and implemented the following code snippet (found within an AJAX call success function, where info.userName is a value fetched from my backend program): ch ...

Using React: Implementing conditional checks within the render() method of functional Components

When working with my usual React class Components, I typically perform some checks within the render() method before returning conditional html rendering. However, when using a react functional component, I noticed that there is no render() method availabl ...

Is there a way to automatically redirect a webpage based on the URL that is entered

Looking for a solution where a page checks a typed link upon loading, such as: www.test.com/myphp.php=10 If it detects a specific number, it should redirect to another link. For example: Upon finding www.test.com/myphp.php=10, it redirects to www. ...

The Django POST request is rejecting due to a missing or incorrect CSRF token, despite having included the token in the form

I'm encountering a 403 response when making a POST request despite including csrf_token in the data for an AJAX request. I made sure that csrf_token is not empty before sending the request, so everything seems correct. What could be causing this error ...

Viewify - displaying images in v-data-table cells reveals only a portion of the image

I have a challenge with displaying avatars for users in a table. The rows are too small and the images are getting cut off. https://i.sstatic.net/QjkHj.png Table: <v-data-table :headers="tableHeaders" :items="streamers"> <t ...

Altering the href text within a script causes the text to disappear instead of updating

Function Triggered by Button Click: function LoadEnglishText() { document.getElementById("txt_whatwedo_learnmore2").innerHTML = "here."; } HTML Link to be Updated: <a id="txt_whatwedo_learnmore2" href="./pdf/Pricing_App_Dev_2019_Ger.pdf">hier ...

What is the process for applying a border to the chosen image within the ImageList of the MaterialUI component?

Currently, I have set up the images in a grid format using the and components from MaterialUI. However, I am looking to implement an additional feature where when a user clicks on a specific image from the grid, a border is displayed around that select ...

Insert text within the switch component using Material-UI

Looking to customize Material UI's Switch component with text inside? Check out the image below for an idea of what I'm going for. https://i.stack.imgur.com/KadRZ.png Take a look at my code snippet: import React from 'react'; import S ...