0

I have two classes example1 and example2. example1 is having async method inside await keyword and promise response from API. When console inside async function am able to get print this.data and this.data but when I tried this to console inside example2 coming blank response where able to get response for this.key. How to solve this issue. This might be due to resolving promising taking time. Any suggestion ? below is sample example.

One class :

class example1{

constructor(){
  
 this.asyncFunction();
}

async asyncFunction(){
 this.key = await this.callAPI(url);

 this.data = await this.callAPI(url2);
}

callAPI(url) {
    const metadata = new Promise((resolve) => {
      fetch(url).then((res) => {
        const json = res.json();
        // console.log(json);
        resolve(json);
      });
    });
    return metadata;
  }
}


Second class :

import example1; // just added to show it imported class
class example2{

constructor(){
 const a = new example1();
 console(a); // i got all response; 
 console(a.data) // got blank response; 
}

10
  • Doing anything async in a constructor is a bad idea, because the async operation cannot resolve before the synchronous constructor finishes. You need to rethink your design to not require an async operation in the constructor. Commented Aug 4, 2021 at 8:46
  • 2
    We understand what you want, we can’t tell you how to fix it. As said, what you want is impossible. The two linked duplicates explain why. How to do it differently so it still fits your requirements we can’t tell you. Commented Aug 4, 2021 at 8:50
  • 1
    The duplicates are exactly what you need to understand, please read them, understand them. And then your problem is much easier to fix. One suggestion is create a method called async init(), and then your caller can do const example = new Example(); await example.init().. Or something similar. Commented Aug 4, 2021 at 8:50
  • 2
    Exactly, you’d need to make an async constructor, and do await new Example, and that doesn’t exist. Async operations in constructors = no go. Commented Aug 4, 2021 at 8:57
  • 1
    Or make an async function that fetches the data and then returns a class with that data… Commented Aug 4, 2021 at 9:02

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.