[q] Allow thenReject to return a promise for a different type (#23029)

* Change the Promise.thenReject signature to allow matching of a
  different type.

Type-checking rejections is problematic as it's equivalent to `throw`:
you don't get a value of type T in your success callback. You get
an Error (or other thrown type) in an error callback.
This commit is contained in:
MikeDimmickMnetics
2018-01-19 20:22:15 +00:00
committed by Wesley Wigham
parent d512b1f5d1
commit c686efd51b
2 changed files with 35 additions and 1 deletions

2
types/q/index.d.ts vendored
View File

@@ -145,7 +145,7 @@ declare namespace Q {
/**
* A sugar method, equivalent to promise.then(function () { throw reason; }).
*/
thenReject(reason?: any): Promise<T>;
thenReject<U = T>(reason?: any): Promise<U>;
/**
* Attaches a handler that will observe the value of the promise when it becomes fulfilled, returning a promise for that same value, perhaps deferred but not replaced by the promise returned

View File

@@ -234,3 +234,37 @@ Q.try(() => {
return true;
})
.catch((error) => console.error("Couldn't sync to the cloud", error));
// thenReject, returning a Promise of the same type as the Promise it is called on
function thenRejectSameType(arg: any): Q.Promise<number> {
if (!arg) {
return returnsNumPromise('')
.thenReject(new Error('failed'));
}
return Q.resolve(2);
}
// thenReject, returning a Promise of a different type to the Promise it is called on.
// The generic type argument is specified.
function thenRejectSpecificOtherType(arg: any): Q.Promise<string> {
if (!arg) {
return returnsNumPromise('')
.thenReject<string>(new Error('failed'));
}
return Q.resolve('');
}
// thenReject, returning a Promise of a different type to the Promise it is called on.
// The generic type argument is inferred.
// This relies on 'Return types as inference targets', new in TS 2.4.
// Commented out as we support TS 2.3.
// This should be uncommented if the minimum version is changed.
/*
function thenRejectInferredOtherType(arg: any): Q.Promise<string> {
if (!arg) {
return returnsNumPromise('')
.thenReject(new Error('failed'));
}
return Q.resolve('');
}
*/