4

Is it possible to export the value of an await function from an ES6 class? For example, I have a class with a function named getDetails which looks like this

class Config {
    static async getDetails() {
        let response = await fetch('url/where/details/are')
        let data = await response.json()
        return data;
    }
}

export { Config }

When I import this class into another file, and call User.getDetails(), whats returned is Promise {<pending>}. Is there a way to make the stack wait for a response from the API first?

dave
  • 355
  • 5
  • 11
  • 1
    It sounds like you want to delay your whole application until the config is ready. Which is reasonable. But you need to explicitly tell JavaScript how to do this. You can `.then()` the promise, or use `await`. – Sidney Jan 19 '18 at 19:40
  • What do you mean by "wait for a response from the API first?" ? Before `export`? – guest271314 Jan 19 '18 at 19:44
  • It is a special case and possible duplicate of http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Estus Flask Jan 19 '18 at 19:44

2 Answers2

2

Why not just use await in your parent file too?

// your async function

const res = await User.getDetails()

// here you have res

Alternatively, you can use .then

User.getDetails()
.then(res => {
    // use res here
})
mehulmpt
  • 15,861
  • 12
  • 48
  • 88
0

When calling User.getDetails(), you need to either use .then() or use await. Remember – you can only use await within an async function, so you would either do

async myFunction() {
    const data = await User.getDetails();  
}

or

myFunction() {
    const data = User.getDetails().then(res => {})
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400