Reputation: 355
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?
Upvotes: 4
Views: 3633
Reputation: 281834
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 => {})
}
Upvotes: 0
Reputation: 16587
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
})
Upvotes: 2