Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining promises with Q

Tags:

jquery

promise

q

In jquery, I can combine promises as follows:

var Promise = $.when(func1.execute(), func2.execute());
Promise.done(function (data1, data2) {
// code here
}

How would you rewrite this using Q?

Also. what are the benefits of using Q in this scenario over jquery?

like image 233
LastTribunal Avatar asked Jan 24 '26 20:01

LastTribunal


1 Answers

Simple Answer:

var promise = Q.all([func1.execute(), func2.execute()]);
promise.spread(function (data1, data2) {
  // code here
})
.done();

Annotated:

//make `promise` be a promise for the array
var promise = Q.all([func1.execute(), func2.execute()]);

//use spread to spread the array across the arguments of a function
promise.spread(function (data1, data2) {
  // code here
})
//use done so errors are thrown
.done();

The concepts in Q are much more clearly defined. The promise represents a single value that may not be available yet. This parallels synchronous code very precisely.

To represent multiple values then, we simply use an array. Q.all is a helper method that takes an array of promises, and returns a promise for an array containing their fulfilled values. If any promise in the array is rejected, the resulting promise will also be rejected.

Because in this case we know exactly how long the array is and essentially just want the items separately, it's convenient to use the spread helper provided by Q. When called on a promise for an array, spread takes the items in the array and spreads them out across all the arguments of the function. You could simply have done:

//make `promise` be a promise for the array
var promise = Q.all([func1.execute(), func2.execute()]);
promise.done(function (data) {
  var data1 = data[0];
  var data2 = data[1];
  // code here
});

This is perhaps conceptually simpler, but considerably less clean. I strongly recommend you read through https://github.com/kriskowal/q/wiki/Coming-from-jQuery as this has some really helpful advice to people coming from jQuery. If you find anything in it that can be improved, you can edit it and hopefully help future people making the same transition.

like image 78
ForbesLindesay Avatar answered Jan 27 '26 13:01

ForbesLindesay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!