namespace RSG {
public static class PromiseHelpers {
///
/// Returns a promise that resolves with all of the specified promises have resolved.
/// Returns a promise of a tuple of the resolved results.
///
public static IPromise> All(IPromise p1, IPromise p2) {
var val1 = default(T1);
var val2 = default(T2);
var numUnresolved = 2;
var alreadyRejected = false;
var promise = new Promise>();
p1
.Then(val => {
val1 = val;
numUnresolved--;
if (numUnresolved <= 0) {
promise.Resolve(Tuple.Create(val1, val2));
}
})
.Catch(e => {
if (!alreadyRejected) {
promise.Reject(e);
}
alreadyRejected = true;
})
.Done();
p2
.Then(val => {
val2 = val;
numUnresolved--;
if (numUnresolved <= 0) {
promise.Resolve(Tuple.Create(val1, val2));
}
})
.Catch(e => {
if (!alreadyRejected) {
promise.Reject(e);
}
alreadyRejected = true;
})
.Done();
return promise;
}
///
/// Returns a promise that resolves with all of the specified promises have resolved.
/// Returns a promise of a tuple of the resolved results.
///
public static IPromise> All(IPromise p1, IPromise p2, IPromise p3) {
return All(All(p1, p2), p3)
.Then(vals => Tuple.Create(vals.Item1.Item1, vals.Item1.Item2, vals.Item2));
}
///
/// Returns a promise that resolves with all of the specified promises have resolved.
/// Returns a promise of a tuple of the resolved results.
///
public static IPromise> All(IPromise p1, IPromise p2,
IPromise p3, IPromise p4) {
return All(All(p1, p2), All(p3, p4))
.Then(vals => Tuple.Create(vals.Item1.Item1, vals.Item1.Item2, vals.Item2.Item1, vals.Item2.Item2));
}
}
}