Reputation: 1307
I'm currently trying to run an asynchronous function with a callback inside of my constructor. I then need to get data from that callback and use it when creating an instance of the class. My code currently looks like this:
class Foo extends Bar {
constructor(data) {
someAsyncCall((response) => {
data.a = response;
super(data);
});
}
}
Any help is greatly appreciated :)
Upvotes: 0
Views: 334
Reputation: 221
In my opinion I wouldn't do it inside the constructor. Use the Q library and another helper class as a data access layer.
HelperClass.getFooById(id)
.then(function (data) {
return new Foo(data);
})
The getFooById
method would use Q.defer()
and would call Q.resolve(data)
once the data is resolved.
If you do it inside of the constructor you can never create an instance of that class without making a request, even if you have the data already.
Q Library: https://github.com/kriskowal/q
Upvotes: 1