It seems like the task at hand involves typical mysql/database work.
You might consider restructuring the code in this manner:
this.model = MyModel.find({id:id});
try {
this.doSomething();
} catch (e) {
if (e instanceof SomeSpecificException) {
var fetchPromise = this.model.fetch();
fetchPromise.done(
this.doSomething.bind(this)
);
}
}
Explaining the code snippet:
The try/catch statement is useful for identifying when something is not found or does not exist. If an error is caught, then a fetch operation can be initiated. The fetch should return a future/promise; if it doesn't, you can create a shim to handle it accordingly. Once the promise is resolved, it will call the doSomething function with its scope bound to 'this', eliminating the need for 'self'.
How to create a shim:
A potential solution could be:
var Deferred = require('simply-deferred');
Backbone.Model.prototype.fetch = function(options) {
var dfd = Deferred();
Backbone.Model.prototype.fetch.call(
this,
_.extend({ success: dfd.resolve.bind(this) }, options)
);
return dfd.promise;
}
The only uncertainty lies in which function to utilize; using Backbone.Model.prototype.fetch may refer to the original Backbone fetch method. The goal is to invoke the Backbone-Relational fetch method, passing your options and scope, while ensuring the success option resolves the promise.
Why isn't this functionality built-in? Well, individuals in the node.js community opted against making promises the default approach, potentially leaving developers dealing with callback hell.