As my code shows, I currently am passing a promise down two asynchronous callbacks functions (success and callback). I think it should be possible to do this differently, but I have found no other way yet.
Here is my function that creates the promises and waits for them all to be done:
_onModelLoaded: function(model) {
var promises = [];
_.each(this._customRecords, function(defect, index) {
promises.push(this._getHistory(model, defect));
}, this);
Deft.Promise.all(promises).then({
success: function(something) {
console.log('woot',something);
}
});
},
The _getHistory
function creates a promise, then passes it into two functions (_onHistoryLoaded and _onRevisionsLoaded) so that once these callbacks are run, the promise gets resolved:
_getHistory: function(model,defect) {
var deferred = Ext.create('Deft.promise.Deferred');
model.load(Rally.util.Ref.getOidFromRef(defect.RevisionHistory), {
scope: this,
success: function(record) {
this._onHistoryLoaded(defect, record, deferred);
}
});
return deferred.promise;
},
_onHistoryLoaded: function(defect, record, def) {
record.getCollection('Revisions').load({
fetch: ['RevisionNumber', 'CreationDate', 'User', 'Description'],
scope: this,
callback: function(revisions) {
this._onRevisionsLoaded(revisions, defect, def);
}
});
},
_onRevisionsLoaded: function(revisions, defect, def) {
_.each(revisions, function(revision, revisionIndex) {
// Do stuff with each revision
}, this);
def.resolve(defect);
},
I do not necessarily need the final defect to be passed through the promise, I just put it in the resolve statement for testing.
Note: My code does run properly, I am just looking for simplification.
Is there a way to avoid creating a promise only to pass it through a few async functions to get it resolved?