Fiddle: http://jsfiddle.net/smartdev101/eLxxpjp3/
Inside asyncAction function call, a promise has been created to sequence two async operations, getRecords
and getTotal
followed by a final call to onResult(data)
on success or onFail(info)
in case of exception.
how to get onResult call upon completion of two async operations?
asyncAction: function(url, params, resultFunction, faultFunction) {
puremvc.asyncproxy.AsyncProxy.prototype.asyncAction.call(this, resultFunction, faultFunction);
if(!params.id) { //get master
var queryString = this.url.parse(url, true).query;
var offset = queryString.offset ? Number(queryString.offset) : 0;
var limit = queryString.limit ? Number(queryString.limit) : 20;
var data = {rows: null, total: null};
var self = this;
this.getRecords(data, offset, limit)
.then(function(data){return self.getTotal(data)})
//.fail(function(error){self.onFault(error)})
.done(function(data){self.onResult(data)})
} else { //get detail
this.getDetail(params.id);
}
},
getRecords: function(data, offset, limit) {
console.log('get records');
var defer = this.q.defer();
this.connection.query("SELECT title, name, company FROM speaker LIMIT ? OFFSET ?", [limit, offset], function(error, rows, fields){
console.log('get records done');
data.rows = rows;
defer.resolve(data);
//defer.reject("earlier");
});
return defer.promise;
},
getTotal: function(data) {
console.log('get total');
var defer = this.q.defer();
this.connection.query("SELECT * FROM speaker", function(error, rows, fields) { //SQL_CALC_FOUND_ROWS later
data.total = rows.length;
console.log('get total done');
defer.resolve(data);
//defer.reject("just like that");
});
return defer.promise;
},
onResult: function(data) {
console.log('on result');
puremvc.asyncproxy.AsyncProxy.prototype.onResult.call(this, data);
},
onFault: function(info) {
puremvc.asyncproxy.AsyncProxy.prototype.onFault.call(this, info);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…