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.