Here's a query for you. Can I do the following:
class MyClass {
async constructor(){
return new Promise()
}
}
Here's a query for you. Can I do the following:
class MyClass {
async constructor(){
return new Promise()
}
}
Building upon the insights of Patrick Roberts, it is important to note that while you may not be able to directly achieve what you are requesting, a workaround solution can look something like this:
class MyClass {
constructor() {
// Include static initialization logic here
}
async initialize() {
await WhatEverYouWant();
}
static async create() {
const o = new MyClass();
await o.initialize();
return o;
}
}
To implement the above solution in your code, instantiate your object as follows:
const obj = await MyClass.create();
Instead of trying to predict future decisions, let's focus on what we already know and the practical aspects.
Similar to ES6, ES7 aims to expand the language in a backwards compatible way. Essentially, a backwards compatible constructor function is just like a regular function (with some restrictions at runtime) that should be called with the new
keyword. In this scenario, non-object return values are ignored and the newly allocated object is returned, while object return values are simply returned as they are (and the new object is discarded). Therefore, running your code would result in the promise being returned without actual "object construction." It doesn't seem very practical, and anyone who tries to make use of such code will likely face rejection.
To sum it up:
async constructor
may present conflicting ideas.To retrieve a promise from the returned value, use the following code:
class User {
constructor() {
this.promise = this._initialize()
}
async _initialize() {
const response = await fetch('https://jsonplaceholder.typicode.com/users')
const users = await response.json()
this.user = users[Math.floor(Math.random() * users.length)]
}
}
(async () => {
const user = new User()
await user.promise
return user
})().then(u => {
$('#result').text(JSON.stringify(u.user, null, 2))
}).catch(err => {
console.error(err)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="result"><code></code></pre>
I have an array of objects with nested data that includes product, task, instrument details, and assets. I am attempting to locate a specific instrument by supplier ID and modify its asset values based on a given number. const data = [ { // Data for ...
I'm diving into firebase and utilizing react, and currently I've come across this snippet of code: {photos.map(url => ( <div key={url} style={card}> <img src={url} style={image} /> <div s ...
As a newcomer to Node.js, I decided to create a chat application as a hands-on learning experience. My choice of library was ws. During my experiment, I discovered that Node.js code doesn't work directly in browsers, especially when it comes to requi ...
I developed a web application that functions as a messaging system, where users can submit messages and others can receive them. The system operates through AJAX, with the front end using JavaScript to interact with a PHP backend. Everything runs smoothly ...
In my web application, there is a search field that allows users to enter tags for searching. The window should pop up directly below the search field as shown in this image: Image I am trying to figure out how the window positioning is actually d ...
Can someone assist me with sending data to a form in this format? <form id="money" action="" method="post"> <input id="user" type="text" placeholder="Username" maxlenght="10" name="user"></input> <div class="select"> <select id= ...
In my current project, I am using Python/Django for the backend with a complex structure of forms. The frontend consists of an Angular controller that makes requests to fetch a suitable form. While working on this, I came across a Django-Angular package th ...
Currently, I am facing challenges with styling and organization while working on a new react project with material ui and styled components. Despite researching best practices for styled components, I am still struggling to find an effective solution for s ...
It's surprising that I haven't found answers to my specific questions despite searching extensively. I have an Expenses page where I want to display all expenses for a given month in a table. Currently, I achieve this by adding month and year par ...
My current project involves a table with unique column select drop-downs provided by an amazing jQuery plug-in. The performance is excellent with about 1000 rows. However, the client just informed me that the data could increase to 40000 rows within a mont ...
I'm working on creating a dynamic search feature. As the user types in the search box, JavaScript is triggered to hide the blog posts (#home) and display search results instead (the specific script for this is not shown below). However, when the user ...
When I receive a json from a URL containing numerous objects, how can I extract only the slugs provided in the json below? I am open to solutions using either PHP or JavaScript. On one hand, I need to understand how to specifically retrieve the desired ob ...
I'm currently using Angular 1.3.0rc2 and facing an issue with setting one input field based on another input field after the blur event. When I try to set the value of an input field that only has a synchronous validator, everything works fine by usi ...
I have included redux-persist in my project, but for some reason it is not persisting the state as expected. Instead, I keep receiving the initial state whenever I reload the page. Below is the snippet of my root-reducer: import { combineReducers } from & ...
I am hoping to automatically fill a hidden text field with the URL of the current page so that I can keep track of where form submissions are coming from. This simple solution will help me streamline my inquiry responses and save time. To clarify, upon lo ...
Receiving "chunked" data (json arrays) on the front-end via "xhr" (onprogress). Handling delayed chunks is easy - just remember response length and offset. The challenge comes when multiple "chunked" responses arrive simultaneously, resulting in an unpars ...
I'm encountering a problem with my bar chart created using chart.js - the responsive feature works well for some elements but not all. Specifically, the labels on my bar chart do not resize along with the window, resulting in a strange look at smaller ...
Utilizing the "Tempus Dominus Bootstrap 4" for time manipulation has been a crucial part of my workflow. Recently, I encountered a bug while implementing a function to clear all input values upon clicking a specific button. Unfortunately, the clear funct ...
I am currently working on implementing an Angular Material Slide Toggle feature. I want to display a confirmation message if the user tries to switch the toggle from true to false, ensuring they really intend to do this. If the user chooses to cancel, I&ap ...
I need help filtering my JSON data based on multiple categories using Vuejs, specifically with Vue 3 and collect.js. Here's the template I'm working with: <select v-model="selectedCategory" multiple> <option :value="n ...