I'm trying to untangle a huge mess of callback-based code for node and it seems like promises hold the key to that as I have lots of async database operations. Specifically I am using Bluebird.
I am stuck on how to handle a function which needs to either retrieve data from the DB and set certain values on this
. The end goal I am trying to accomplish is something like:
myobj.init().then(function() {
return myobj.doStuff1();
}).then(function() {
return myobj.doStuff2();
}).catch(function(err) {
console.log("Bad things happened!", err);
});
Particularly init
, doStuff1
and doStuff2
need to run only when the previous one has completed, but they all do (multiple) asynchronous operations.
This is what I have for init so far, but I don't know how to finish it:
Thing.prototype.init = function(force) {
if (!this.isInitialized || force) {
return datbase.query("...").then(function(results){
// ... use results to configure this
}).catch(function(err){
console.log("Err 01");
throw err;
});
} else {
// ???
// No data needs to be retrieved from the DB and no data needs to be returned per-se because it's all stored in properties of this.
// But how do I return something that is compatible with the other return path?
}
}
Edit: While the duplicated question linked explained a similar pattern, it didn't quite answer my problem as it didn't make it clear I could resolve a promise with nothing.