jquery - Combining promises with Q -
in jquery, can combine promises follows:
var promise = $.when(func1.execute(), func2.execute()); promise.done(function (data1, data2) { // code here }
how rewrite using q?
also. benefits of using q in scenario on jquery?
simple answer:
var promise = q.all([func1.execute(), func2.execute()]); promise.spread(function (data1, data2) { // code here }) .done();
annotated:
//make `promise` promise array var promise = q.all([func1.execute(), func2.execute()]); //use spread spread array across arguments of function promise.spread(function (data1, data2) { // code here }) //use done errors thrown .done();
the concepts in q
more defined. promise represents single value may not available yet. parallels synchronous code precisely.
to represent multiple values then, use array. q.all
helper method takes array of promises, , returns promise array containing fulfilled values. if promise in array rejected, resulting promise rejected.
because in case know how long array , want items separately, it's convenient use spread
helper provided q
. when called on promise array, spread takes items in array , spreads them out across arguments of function. have done:
//make `promise` promise array var promise = q.all([func1.execute(), func2.execute()]); promise.done(function (data) { var data1 = data[0]; var data2 = data[1]; // code here });
this perhaps conceptually simpler, considerably less clean. recommend read through https://github.com/kriskowal/q/wiki/coming-from-jquery has helpful advice people coming jquery. if find in can improved, can edit , future people making same transition.
Comments
Post a Comment