I am new to node and I'm currently wrestling with finding the most iodomatic way to create an object whose construction depends on the results of an http query. The object is useless until the query is returned and parsed successfully so it feels wrong to return from the constructor without my object being initialized but everything I've read about node says I should keep things asynchronous.
I could either write it synchronously like this (pardon the pseudocode)
function FooConfig(cfg_url) {
// use httpsync to get the response synchronously
var response = get(cfg_url);
if (response.is_good()) {
// parse response and set member data from response
this.bar = response.bar
} else {
// Raise an error
}
};
or asynchronously
function FooConfig(cfg_url) {
// Use the regular http module and make the request asynchronously
var newCfg = this;
http.get(cfg_url, function(response) {
if (response.is_good()) {
newCfg.bar = respsonse.bar
} else {
// Raise an error
}
});
});
The problem with the async version is that any client code that depends on an instance of FooCfg might fail if the request is not completed.
i.e.
var myCfg = new FooCfg('www.someurl.com/config')
// request is still pending
var myDependentObject = new DependsOnConfig(cfg); // Error, this neeeds myCfg.bar
Is this an instance where its ok to be synchronous? this should only happen once when the node application is being initialized.