diff --git a/types/q/index.d.ts b/types/q/index.d.ts index 56ada9590a..942d5535ec 100644 --- a/types/q/index.d.ts +++ b/types/q/index.d.ts @@ -1,6 +1,9 @@ // Type definitions for Q 1.0 // Project: https://github.com/kriskowal/q -// Definitions by: Barrie Nemetchek , Andrew Gaspar , John Reilly +// Definitions by: Barrie Nemetchek +// Andrew Gaspar +// John Reilly +// Michel Boudreau // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -10,343 +13,371 @@ export as namespace Q; /** * If value is a Q promise, returns the promise. * If value is a promise from another library it is coerced into a Q promise (where possible). - */ -declare function Q(promise: PromiseLike): Q.Promise; -/** * If value is not a promise, returns a promise that is fulfilled with value. */ -declare function Q(value: T): Q.Promise; +declare function Q(promise: PromiseLike | T): Q.Promise; /** * Calling with nothing at all creates a void promise */ declare function Q(): Q.Promise; declare namespace Q { + export type IWhenable = PromiseLike | T; + export type IPromise = PromiseLike; - export type IWhenable = PromiseLike | T; - export type IPromise = PromiseLike; + export interface Deferred { + promise: Promise; - export interface Deferred { - promise: Promise; - resolve(value?: IWhenable): void; - reject(reason: any): void; - notify(value: any): void; - makeNodeResolver(): (reason: any, value: T) => void; - } + resolve(value?: IWhenable): void; - export interface Promise { - /** - * Like a finally clause, allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful for collecting resources regardless of whether a job succeeded, like closing a database connection, shutting a server down, or deleting an unneeded key from an object. + reject(reason: any): void; - * finally returns a promise, which will become resolved with the same fulfillment value or rejection reason as promise. However, if callback returns a promise, the resolution of the returned promise will be delayed until the promise returned from callback is finished. - */ - fin(finallyCallback: () => any): Promise; - /** - * Like a finally clause, allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful for collecting resources regardless of whether a job succeeded, like closing a database connection, shutting a server down, or deleting an unneeded key from an object. + notify(value: any): void; - * finally returns a promise, which will become resolved with the same fulfillment value or rejection reason as promise. However, if callback returns a promise, the resolution of the returned promise will be delayed until the promise returned from callback is finished. - */ - finally(finallyCallback: () => any): Promise; + makeNodeResolver(): (reason: any, value: T) => void; + } - /** - * The then method from the Promises/A+ specification, with an additional progress handler. - */ - then(onFulfill?: (value: T) => IWhenable, onReject?: (error: any) => IWhenable, onProgress?: Function): Promise; + export interface Promise { + /** + * Like a finally clause, allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful for collecting resources + * regardless of whether a job succeeded, like closing a database connection, shutting a server down, or deleting an unneeded key from an object. finally returns a promise, which will become + * resolved with the same fulfillment value or rejection reason as promise. However, if callback returns a promise, the resolution of the returned promise will be delayed until the promise + * returned from callback is finished. + */ + fin(finallyCallback: () => any): Promise; - /** - * Like then, but "spreads" the array into a variadic fulfillment handler. If any of the promises in the array are rejected, instead calls onRejected with the first rejected promise's rejection reason. - * - * This is especially useful in conjunction with all - */ - spread(onFulfill: (...args: any[]) => IWhenable, onReject?: (reason: any) => IWhenable): Promise; + /** + * Like a finally clause, allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful for collecting resources + * regardless of whether a job succeeded, like closing a database connection, shutting a server down, or deleting an unneeded key from an object. finally returns a promise, which will become + * resolved with the same fulfillment value or rejection reason as promise. However, if callback returns a promise, the resolution of the returned promise will be delayed until the promise + * returned from callback is finished. + */ + finally(finallyCallback: () => any): Promise; - fail(onRejected: (reason: any) => IWhenable): Promise; + /** + * The then method from the Promises/A+ specification, with an additional progress handler. + */ + then(onFulfill?: (value: T) => IWhenable, onReject?: (error: any) => IWhenable, onProgress?: (progress: any) => any): Promise; - /** - * A sugar method, equivalent to promise.then(undefined, onRejected). - */ - catch(onRejected: (reason: any) => IWhenable): Promise; + /** + * Like then, but "spreads" the array into a variadic fulfillment handler. If any of the promises in the array are rejected, instead calls onRejected with the first rejected promise's + * rejection reason. + * + * This is especially useful in conjunction with all + */ + spread(onFulfill: (...args: any[]) => IWhenable, onReject?: (reason: any) => IWhenable): Promise; - /** - * A sugar method, equivalent to promise.then(undefined, undefined, onProgress). - */ - progress(onProgress: (progress: any) => any): Promise; + fail(onRejected: (reason: any) => IWhenable): Promise; - /** - * Much like then, but with different behavior around unhandled rejection. If there is an unhandled rejection, either because promise is rejected and no onRejected callback was provided, or because onFulfilled or onRejected threw an error or returned a rejected promise, the resulting rejection reason is thrown as an exception in a future turn of the event loop. - * - * This method should be used to terminate chains of promises that will not be passed elsewhere. Since exceptions thrown in then callbacks are consumed and transformed into rejections, exceptions at the end of the chain are easy to accidentally, silently ignore. By arranging for the exception to be thrown in a future turn of the event loop, so that it won't be caught, it causes an onerror event on the browser window, or an uncaughtException event on Node.js's process object. - * - * Exceptions thrown by done will have long stack traces, if Q.longStackSupport is set to true. If Q.onerror is set, exceptions will be delivered there instead of thrown in a future turn. - * - * The Golden Rule of done vs. then usage is: either return your promise to someone else, or if the chain ends with you, call done to terminate it. - */ - done(onFulfilled?: (value: T) => any, onRejected?: (reason: any) => any, onProgress?: (progress: any) => any): void; + /** + * A sugar method, equivalent to promise.then(undefined, onRejected). + */ + catch(onRejected: (reason: any) => IWhenable): Promise; - /** - * If callback is a function, assumes it's a Node.js-style callback, and calls it as either callback(rejectionReason) when/if promise becomes rejected, or as callback(null, fulfillmentValue) when/if promise becomes fulfilled. If callback is not a function, simply returns promise. - */ - nodeify(callback: (reason: any, value: any) => void): Promise; + /** + * A sugar method, equivalent to promise.then(undefined, undefined, onProgress). + */ + progress(onProgress: (progress: any) => any): Promise; - /** - * Returns a promise to get the named property of an object. Essentially equivalent to - * - * promise.then(function (o) { - * return o[propertyName]; - * }); - */ - get(propertyName: String): Promise; - set(propertyName: String, value: any): Promise; - delete(propertyName: String): Promise; - /** - * Returns a promise for the result of calling the named method of an object with the given array of arguments. The object itself is this in the function, just like a synchronous method call. Essentially equivalent to - * - * promise.then(function (o) { - * return o[methodName].apply(o, args); - * }); - */ - post(methodName: String, args: any[]): Promise; - /** - * Returns a promise for the result of calling the named method of an object with the given variadic arguments. The object itself is this in the function, just like a synchronous method call. - */ - invoke(methodName: String, ...args: any[]): Promise; - fapply(args: any[]): Promise; - fcall(...args: any[]): Promise; + /** + * Much like then, but with different behavior around unhandled rejection. If there is an unhandled rejection, either because promise is rejected and no onRejected callback was provided, or + * because onFulfilled or onRejected threw an error or returned a rejected promise, the resulting rejection reason is thrown as an exception in a future turn of the event loop. + * + * This method should be used to terminate chains of promises that will not be passed elsewhere. Since exceptions thrown in then callbacks are consumed and transformed into rejections, + * exceptions at the end of the chain are easy to accidentally, silently ignore. By arranging for the exception to be thrown in a future turn of the event loop, so that it won't be caught, it + * causes an onerror event on the browser window, or an uncaughtException event on Node.js's process object. + * + * Exceptions thrown by done will have long stack traces, if Q.longStackSupport is set to true. If Q.onerror is set, exceptions will be delivered there instead of thrown in a future turn. + * + * The Golden Rule of done vs. then usage is: either return your promise to someone else, or if the chain ends with you, call done to terminate it. + */ + done(onFulfilled?: (value: T) => any, onRejected?: (reason: any) => any, onProgress?: (progress: any) => any): void; - /** - * Returns a promise for an array of the property names of an object. Essentially equivalent to - * - * promise.then(function (o) { - * return Object.keys(o); - * }); - */ - keys(): Promise; + /** + * If callback is a function, assumes it's a Node.js-style callback, and calls it as either callback(rejectionReason) when/if promise becomes rejected, or as callback(null, fulfillmentValue) + * when/if promise becomes fulfilled. If callback is not a function, simply returns promise. + */ + nodeify(callback: (reason: any, value: any) => void): Promise; - /** - * A sugar method, equivalent to promise.then(function () { return value; }). - */ - thenResolve(value: U): Promise; - /** - * A sugar method, equivalent to promise.then(function () { throw reason; }). - */ - thenReject(reason: any): Promise; + /** + * Returns a promise to get the named property of an object. Essentially equivalent to + * + * @example + * promise.then(function (o) { return o[propertyName]; }); + */ + get(propertyName: string): Promise; - /** - * 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 by the onFulfilled handler. - */ - tap(onFulfilled: (value: T) => any): Promise; + set(propertyName: string, value: any): Promise; - timeout(ms: number, message?: string): Promise; - /** - * Returns a promise that will have the same result as promise, but will only be fulfilled or rejected after at least ms milliseconds have passed. - */ - delay(ms: number): Promise; + delete(propertyName: string): Promise; - /** - * Returns whether a given promise is in the fulfilled state. When the static version is used on non-promises, the result is always true. - */ - isFulfilled(): boolean; - /** - * Returns whether a given promise is in the rejected state. When the static version is used on non-promises, the result is always false. - */ - isRejected(): boolean; - /** - * Returns whether a given promise is in the pending state. When the static version is used on non-promises, the result is always false. - */ - isPending(): boolean; + /** + * Returns a promise for the result of calling the named method of an object with the given array of arguments. The object itself is this in the function, just like a synchronous method call. + * Essentially equivalent to + * + * @example + * promise.then(function (o) { return o[methodName].apply(o, args); }); + */ + post(methodName: string, args: any[]): Promise; - valueOf(): any; + /** + * Returns a promise for the result of calling the named method of an object with the given variadic arguments. The object itself is this in the function, just like a synchronous method call. + */ + invoke(methodName: string, ...args: any[]): Promise; - /** - * Returns a "state snapshot" object, which will be in one of three forms: - * - * - { state: "pending" } - * - { state: "fulfilled", value: } - * - { state: "rejected", reason: } - */ - inspect(): PromiseState; - } + fapply(args: any[]): Promise; - export interface PromiseState { - state: "fulfilled" | "rejected" | "pending"; - value?: T; - reason?: any; - } + fcall(...args: any[]): Promise; - // If no value provided, returned promise will be of void type - export function when(): Promise; + /** + * Returns a promise for an array of the property names of an object. Essentially equivalent to + * + * @example + * promise.then(function (o) { return Object.keys(o); }); + */ + keys(): Promise; - // if no fulfill, reject, or progress provided, returned promise will be of same type - export function when(value: IWhenable): Promise; + /** + * A sugar method, equivalent to promise.then(function () { return value; }). + */ + thenResolve(value: U): Promise; - // If a non-promise value is provided, it will not reject or progress - export function when(value: IWhenable, onFulfilled: (val: T) => IWhenable, onRejected?: (reason: any) => IWhenable, onProgress?: (progress: any) => any): Promise; + /** + * A sugar method, equivalent to promise.then(function () { throw reason; }). + */ + thenReject(reason: any): Promise; - function _try(method: Function, ...args: any[]): Promise; - export { _try as try }; + /** + * 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 + * by the onFulfilled handler. + */ + tap(onFulfilled: (value: T) => any): Promise; - export function fbind(method: (...args: any[]) => IWhenable, ...args: any[]): (...args: any[]) => Promise; + timeout(ms: number, message?: string): Promise; - export function fcall(method: (...args: any[]) => T, ...args: any[]): Promise; + /** + * Returns a promise that will have the same result as promise, but will only be fulfilled or rejected after at least ms milliseconds have passed. + */ + delay(ms: number): Promise; - export function send(obj: any, functionName: string, ...args: any[]): Promise; - export function invoke(obj: any, functionName: string, ...args: any[]): Promise; - export function mcall(obj: any, functionName: string, ...args: any[]): Promise; + /** + * Returns whether a given promise is in the fulfilled state. When the static version is used on non-promises, the result is always true. + */ + isFulfilled(): boolean; - export function denodeify(nodeFunction: Function, ...args: any[]): (...args: any[]) => Promise; - export function nbind(nodeFunction: Function, thisArg: any, ...args: any[]): (...args: any[]) => Promise; - export function nfbind(nodeFunction: Function, ...args: any[]): (...args: any[]) => Promise; - export function nfcall(nodeFunction: Function, ...args: any[]): Promise; - export function nfapply(nodeFunction: Function, args: any[]): Promise; + /** + * Returns whether a given promise is in the rejected state. When the static version is used on non-promises, the result is always false. + */ + isRejected(): boolean; - export function ninvoke(nodeModule: any, functionName: string, ...args: any[]): Promise; - export function npost(nodeModule: any, functionName: string, args: any[]): Promise; - export function nsend(nodeModule: any, functionName: string, ...args: any[]): Promise; - export function nmcall(nodeModule: any, functionName: string, ...args: any[]): Promise; + /** + * Returns whether a given promise is in the pending state. When the static version is used on non-promises, the result is always false. + */ + isPending(): boolean; - /** - * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. - */ - export function all(promises: IWhenable<[IWhenable, IWhenable, IWhenable, IWhenable, IWhenable, IWhenable]>): Promise<[A, B, C, D, E, F]>; - /** - * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. - */ - export function all(promises: IWhenable<[IWhenable, IWhenable, IWhenable, IWhenable, IWhenable]>): Promise<[A, B, C, D, E]>; - /** - * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. - */ - export function all(promises: IWhenable<[IWhenable, IWhenable, IWhenable, IWhenable]>): Promise<[A, B, C, D]>; - /** - * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. - */ - export function all(promises: IWhenable<[IWhenable, IWhenable, IWhenable]>): Promise<[A, B, C]>; - /** - * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. - */ - export function all(promises: IWhenable<[IPromise, IPromise]>): Promise<[A, B]>; - export function all(promises: IWhenable<[A, IPromise]>): Promise<[A, B]>; - export function all(promises: IWhenable<[IPromise, B]>): Promise<[A, B]>; - export function all(promises: IWhenable<[A, B]>): Promise<[A, B]>; - /** - * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. - */ - export function all(promises: IWhenable[]>): Promise; + valueOf(): any; - /** - * Returns a promise for the first of an array of promises to become settled. - */ - export function race(promises: IWhenable[]): Promise; + /** + * Returns a "state snapshot" object, which will be in one of three forms: + * + * - { state: "pending" } + * - { state: "fulfilled", value: } + * - { state: "rejected", reason: } + */ + inspect(): PromiseState; + } - /** - * Returns a promise that is fulfilled with an array of promise state snapshots, but only after all the original promises have settled, i.e. become either fulfilled or rejected. - */ - export function allSettled(promises: IWhenable[]>): Promise[]>; + export interface PromiseState { + state: "fulfilled" | "rejected" | "pending"; + value?: T; + reason?: any; + } - export function allResolved(promises: IWhenable[]>): Promise[]>; + // If no value provided, returned promise will be of void type + export function when(): Promise; - /** - * Like then, but "spreads" the array into a variadic fulfillment handler. If any of the promises in the array are rejected, instead calls onRejected with the first rejected promise's rejection reason. - * This is especially useful in conjunction with all. - */ - export function spread(promises: IWhenable[], onFulfilled: (...args: T[]) => IWhenable, onRejected?: (reason: any) => IWhenable): Promise; + // if no fulfill, reject, or progress provided, returned promise will be of same type + export function when(value: IWhenable): Promise; - /** - * Returns a promise that will have the same result as promise, except that if promise is not fulfilled or rejected before ms milliseconds, the returned promise will be rejected with an Error with the given message. If message is not supplied, the message will be "Timed out after " + ms + " ms". - */ - export function timeout(promise: Promise, ms: number, message?: string): Promise; + // If a non-promise value is provided, it will not reject or progress + export function when(value: IWhenable, onFulfilled: (val: T) => IWhenable, onRejected?: (reason: any) => IWhenable, onProgress?: (progress: any) => any): Promise; - /** - * Returns a promise that will have the same result as promise, but will only be fulfilled or rejected after at least ms milliseconds have passed. - */ - export function delay(promise: Promise, ms: number): Promise; - /** - * Returns a promise that will have the same result as promise, but will only be fulfilled or rejected after at least ms milliseconds have passed. - */ - export function delay(value: T, ms: number): Promise; - /** - * Returns a promise that will be fulfilled with undefined after at least ms milliseconds have passed. - */ - export function delay(ms: number): Promise ; - /** - * Returns whether a given promise is in the fulfilled state. When the static version is used on non-promises, the result is always true. - */ - export function isFulfilled(promise: Promise): boolean; - /** - * Returns whether a given promise is in the rejected state. When the static version is used on non-promises, the result is always false. - */ - export function isRejected(promise: Promise): boolean; - /** - * Returns whether a given promise is in the pending state. When the static version is used on non-promises, the result is always false. - */ - export function isPending(promise: Promise): boolean; + export function fbind(method: (...args: any[]) => IWhenable, ...args: any[]): (...args: any[]) => Promise; - /** - * Returns a "deferred" object with a: - * promise property - * resolve(value) method - * reject(reason) method - * notify(value) method - * makeNodeResolver() method - */ - export function defer(): Deferred; + export function fcall(method: (...args: any[]) => T, ...args: any[]): Promise; - /** - * Returns a promise that is rejected with reason. - */ - export function reject(reason?: any): Promise; + // Try is an alias for fcall, but 'try' is a reserved word. This is the only way to get around this + export {fcall as try}; - export function Promise(resolver: (resolve: (val: IWhenable) => void , reject: (reason: any) => void , notify: (progress: any) => void ) => void ): Promise; + export function send(obj: any, functionName: string, ...args: any[]): Promise; - /** - * Creates a new version of func that accepts any combination of promise and non-promise values, converting them to their fulfillment values before calling the original func. The returned version also always returns a promise: if func does a return or throw, then Q.promised(func) will return fulfilled or rejected promise, respectively. - * - * This can be useful for creating functions that accept either promises or non-promise values, and for ensuring that the function always returns a promise even in the face of unintentional thrown exceptions. - */ - export function promised(callback: (...args: any[]) => T): (...args: any[]) => Promise; + export function invoke(obj: any, functionName: string, ...args: any[]): Promise; - /** - * Returns whether the given value is a Q promise. - */ - export function isPromise(object: any): boolean; - /** - * Returns whether the given value is a promise (i.e. it's an object with a then function). - */ - export function isPromiseAlike(object: any): boolean; - /** - * Returns whether a given promise is in the pending state. When the static version is used on non-promises, the result is always false. - */ - export function isPending(object: any): boolean; - /** - * If an object is not a promise, it is as "near" as possible. - * If a promise is rejected, it is as "near" as possible too. - * If it’s a fulfilled promise, the fulfillment value is nearer. - * If it’s a deferred promise and the deferred has been resolved, the - * resolution is "nearer". - */ - export function nearer(promise: Promise): T; + export function mcall(obj: any, functionName: string, ...args: any[]): Promise; - /** - * This is an experimental tool for converting a generator function into a deferred function. This has the potential of reducing nested callbacks in engines that support yield. - */ - export function async(generatorFunction: any): (...args: any[]) => Promise; - export function nextTick(callback: Function): void; + export function denodeify(nodeFunction: (...args: any[]) => any, ...args: any[]): (...args: any[]) => Promise; - /** - * A settable property that will intercept any uncaught errors that would otherwise be thrown in the next tick of the event loop, usually as a result of done. Can be useful for getting the full stack trace of an error in browsers, which is not usually possible with window.onerror. - */ - export var onerror: (reason: any) => void; - /** - * A settable property that lets you turn on long stack trace support. If turned on, "stack jumps" will be tracked across asynchronous promise operations, so that if an uncaught error is thrown by done or a rejection reason's stack property is inspected in a rejection callback, a long stack trace is produced. - */ - export var longStackSupport: boolean; + export function nbind(nodeFunction: (...args: any[]) => any, thisArg: any, ...args: any[]): (...args: any[]) => Promise; - /** - * Calling resolve with a pending promise causes promise to wait on the passed promise, becoming fulfilled with its fulfillment value or rejected with its rejection reason (or staying pending forever, if the passed promise does). - * Calling resolve with a rejected promise causes promise to be rejected with the passed promise's rejection reason. - * Calling resolve with a fulfilled promise causes promise to be fulfilled with the passed promise's fulfillment value. - * Calling resolve with a non-promise value causes promise to be fulfilled with that value. - */ - export function resolve(object: IWhenable): Promise; + export function nfbind(nodeFunction: (...args: any[]) => any, ...args: any[]): (...args: any[]) => Promise; + + export function nfcall(nodeFunction: (...args: any[]) => any, ...args: any[]): Promise; + + export function nfapply(nodeFunction: (...args: any[]) => any, args: any[]): Promise; + + export function ninvoke(nodeModule: any, functionName: string, ...args: any[]): Promise; + + export function npost(nodeModule: any, functionName: string, args: any[]): Promise; + + export function nsend(nodeModule: any, functionName: string, ...args: any[]): Promise; + + export function nmcall(nodeModule: any, functionName: string, ...args: any[]): Promise; + + /** + * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. + */ + export function all(promises: IWhenable<[IWhenable, IWhenable, IWhenable, IWhenable, IWhenable, IWhenable]>): Promise<[A, B, C, D, E, F]>; + /** + * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. + */ + export function all(promises: IWhenable<[IWhenable, IWhenable, IWhenable, IWhenable, IWhenable]>): Promise<[A, B, C, D, E]>; + /** + * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. + */ + export function all(promises: IWhenable<[IWhenable, IWhenable, IWhenable, IWhenable]>): Promise<[A, B, C, D]>; + /** + * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. + */ + export function all(promises: IWhenable<[IWhenable, IWhenable, IWhenable]>): Promise<[A, B, C]>; + /** + * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. + */ + export function all(promises: IWhenable<[IPromise, IPromise]>): Promise<[A, B]>; + export function all(promises: IWhenable<[A, IPromise]>): Promise<[A, B]>; + export function all(promises: IWhenable<[IPromise, B]>): Promise<[A, B]>; + export function all(promises: IWhenable<[A, B]>): Promise<[A, B]>; + /** + * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. + */ + export function all(promises: IWhenable>>): Promise; + + /** + * Returns a promise for the first of an array of promises to become settled. + */ + export function race(promises: Array>): Promise; + + /** + * Returns a promise that is fulfilled with an array of promise state snapshots, but only after all the original promises have settled, i.e. become either fulfilled or rejected. + */ + export function allSettled(promises: IWhenable>>): Promise>>; + + export function allResolved(promises: IWhenable>>): Promise>>; + + /** + * Like then, but "spreads" the array into a variadic fulfillment handler. If any of the promises in the array are rejected, instead calls onRejected with the first rejected promise's rejection + * reason. This is especially useful in conjunction with all. + */ + export function spread(promises: Array>, onFulfilled: (...args: T[]) => IWhenable, onRejected?: (reason: any) => IWhenable): Promise; + + /** + * Returns a promise that will have the same result as promise, except that if promise is not fulfilled or rejected before ms milliseconds, the returned promise will be rejected with an Error + * with the given message. If message is not supplied, the message will be "Timed out after " + ms + " ms". + */ + export function timeout(promise: Promise, ms: number, message?: string): Promise; + + /** + * Returns a promise that will have the same result as promise, but will only be fulfilled or rejected after at least ms milliseconds have passed. + */ + export function delay(promiseOrValue: Promise | T, ms: number): Promise; + /** + * Returns a promise that will be fulfilled with undefined after at least ms milliseconds have passed. + */ + export function delay(ms: number): Promise; + + /** + * Returns whether a given promise is in the fulfilled state. When the static version is used on non-promises, the result is always true. + */ + export function isFulfilled(promise: Promise): boolean; + + /** + * Returns whether a given promise is in the rejected state. When the static version is used on non-promises, the result is always false. + */ + export function isRejected(promise: Promise): boolean; + + /** + * Returns whether a given promise is in the pending state. When the static version is used on non-promises, the result is always false. + */ + export function isPending(promiseOrObject: Promise | any): boolean; + + /** + * Returns a "deferred" object with a: + * promise property + * resolve(value) method + * reject(reason) method + * notify(value) method + * makeNodeResolver() method + */ + export function defer(): Deferred; + + /** + * Returns a promise that is rejected with reason. + */ + export function reject(reason?: any): Promise; + + export function Promise(resolver: (resolve: (val?: IWhenable) => void, reject: (reason: any) => void, notify: (progress: any) => void) => void): Promise; + + /** + * Creates a new version of func that accepts any combination of promise and non-promise values, converting them to their fulfillment values before calling the original func. The returned version + * also always returns a promise: if func does a return or throw, then Q.promised(func) will return fulfilled or rejected promise, respectively. + * + * This can be useful for creating functions that accept either promises or non-promise values, and for ensuring that the function always returns a promise even in the face of unintentional + * thrown exceptions. + */ + export function promised(callback: (...args: any[]) => T): (...args: any[]) => Promise; + + /** + * Returns whether the given value is a Q promise. + */ + export function isPromise(object: any): boolean; + + /** + * Returns whether the given value is a promise (i.e. it's an object with a then function). + */ + export function isPromiseAlike(object: any): boolean; + + /** + * If an object is not a promise, it is as "near" as possible. + * If a promise is rejected, it is as "near" as possible too. + * If it’s a fulfilled promise, the fulfillment value is nearer. + * If it’s a deferred promise and the deferred has been resolved, the + * resolution is "nearer". + */ + export function nearer(promise: Promise): T; + + /** + * This is an experimental tool for converting a generator function into a deferred function. This has the potential of reducing nested callbacks in engines that support yield. + */ + export function async(generatorFunction: any): (...args: any[]) => Promise; + + export function nextTick(callback: (...args: any[]) => any): void; + + /** + * A settable property that will intercept any uncaught errors that would otherwise be thrown in the next tick of the event loop, usually as a result of done. Can be useful for getting the full + * stack trace of an error in browsers, which is not usually possible with window.onerror. + */ + export let onerror: (reason: any) => void; + /** + * A settable property that lets you turn on long stack trace support. If turned on, "stack jumps" will be tracked across asynchronous promise operations, so that if an uncaught error is thrown + * by done or a rejection reason's stack property is inspected in a rejection callback, a long stack trace is produced. + */ + export let longStackSupport: boolean; + + /** + * Calling resolve with a pending promise causes promise to wait on the passed promise, becoming fulfilled with its fulfillment value or rejected with its rejection reason (or staying pending + * forever, if the passed promise does). Calling resolve with a rejected promise causes promise to be rejected with the passed promise's rejection reason. Calling resolve with a fulfilled promise + * causes promise to be fulfilled with the passed promise's fulfillment value. Calling resolve with a non-promise value causes promise to be fulfilled with that value. + */ + export function resolve(object?: IWhenable): Promise; /** * Resets the global "Q" variable to the value it has before Q was loaded. diff --git a/types/q/q-tests.ts b/types/q/q-tests.ts index 5acb354c80..3a5c125f25 100644 --- a/types/q/q-tests.ts +++ b/types/q/q-tests.ts @@ -1,24 +1,24 @@ +/* tslint:disable:no-namespace */ /// - import Q = require('q'); Q(8).then(x => console.log(x.toExponential())); Q().then(() => console.log("nothing")); -var delay = function (delay: number) { - var d = Q.defer(); - setTimeout(d.resolve, delay); - return d.promise; +const delay = (delay: number) => { + let d = Q.defer(); + setTimeout(d.resolve, delay); + return d.promise; }; -Q.when(delay(1000), function (val: void) { - console.log('Hello, World!'); - return; +Q.when(delay(1000), (val) => { + console.log('Hello, World!'); + return; }); // Note from Q documentation: a deferred can be resolved with a value or a promise. -var otherPromise = Q.defer().promise; +const otherPromise = Q.defer().promise; Q.defer().resolve(otherPromise); Q.timeout(Q(new Date()), 1000, "My dates never arrived. :(").then(d => d.toJSON()); @@ -28,75 +28,79 @@ Q.delay(8, 1000).then(x => x.toExponential()); Q.delay(Q("asdf"), 1000).then(x => x.length); Q.delay("asdf", 1000).then(x => x.length); -var eventualAdd = Q.promised((a?: number, b?: number) => a + b); +const eventualAdd = Q.promised((a?: number, b?: number) => a + b); eventualAdd(Q(1), Q(2)).then(x => x.toExponential()); function eventually(eventually: T) { - return Q.delay(eventually, 1000); -}; + return Q.delay(eventually, 1000); +} -var x = Q.all([1, 2, 3].map(eventually)); -Q.when(x, function (x) { - console.log(x); +const x = Q.all([1, 2, 3].map(eventually)); +Q.when(x, (x) => { + console.log(x); }); Q.all([ - eventually(10), - eventually(20) -]).spread(function (x: number, y: number) { - console.log(x, y); + eventually(10), + eventually(20) +]).spread((x: number, y: number) => { + console.log(x, y); }); Q.all([ - eventually(10), - eventually(20) -]).then(function (results) { - let [x, y] = results; - console.log(x, y); + eventually(10), + eventually(20) +]).then((results) => { + let [x, y] = results; + console.log(x, y); }); - -Q.fcall(function () { }) - .then(function () { }) - .then(function () { }) - .then(function () { }) - .then(function (value4) { - // Do something with value4 - }, function (error) { - // Handle any error from step1 through step4 - }).done(); +Q.fcall(() => { +}) + .then(() => { + }) + .then(() => { + }) + .then(() => { + }) + .then((value4) => { + // Do something with value4 + }, (error) => { + // Handle any error from step1 through step4 + }).done(); Q.allResolved([]) -.then(function (promises: Q.Promise[]) { - promises.forEach(function (promise) { - if (promise.isFulfilled()) { - var value = promise.valueOf(); - } else { - var exception = promise.valueOf().exception; - } - }) -}); + .then((promises: Array>) => { + promises.forEach((promise) => { + if (promise.isFulfilled()) { + let value = promise.valueOf(); + } else { + let exception = promise.valueOf().exception; + } + }); + }); Q(42) - .tap(() => "hello") - .tap(x => { - console.log(x); - }) - .then(x => { - console.log("42 == " + x); - }); + .tap(() => "hello") + .tap(x => { + console.log(x); + }) + .then(x => { + console.log("42 == " + x); + }); + +declare let arrayPromise: Q.IPromise; +declare let stringPromise: Q.IPromise; -declare var arrayPromise: Q.IPromise; -declare var stringPromise: Q.IPromise; declare function returnsNumPromise(text: string): Q.Promise; declare function returnsNumPromise(text: string): JQueryPromise; Q(arrayPromise) // type specification required - .then(arr => arr.join(',')) - .then(returnsNumPromise) // requires specification - .then(num => num.toFixed()); + .then(arr => arr.join(',')) + .then(returnsNumPromise) // requires specification + .then(num => num.toFixed()); -declare var jPromise: JQueryPromise; +declare let jPromise: JQueryPromise; // if jQuery promises definition supported generics, this could be more interesting example Q(jPromise).then(str => str.split(',')); @@ -105,9 +109,11 @@ jPromise.then(returnsNumPromise); // watch the typing flow through from jQueryPromise to Q.Promise Q(jPromise).then(str => str.split(',')); -declare var promiseArray: Q.IPromise[]; -var qPromiseArray = promiseArray.map(p => Q(p)); -var myNums: any[] = [2, 3, Q(4), 5, Q(6), Q(7)]; +declare let promiseArray: Array>; +const qPromiseArray = promiseArray.map(p => { + return Q(p); +}); +const myNums: any[] = [2, 3, Q(4), 5, Q(6), Q(7)]; Q.all(promiseArray).then(nums => nums.map(num => num.toPrecision(2)).join(',')); @@ -117,121 +123,116 @@ Q.fbind((dateString?: string) => new Date(dateString), "11/11/1991")().then(d => Q.when(8, num => num + "!"); Q.when(Q(8), num => num + "!").then(str => str.split(',')); -var voidPromise: Q.Promise = Q.when(); +const voidPromise: Q.Promise = Q.when(); declare function saveToDisk(): Q.Promise; -declare function saveToCloud(): Q.Promise; -Q.allSettled([saveToDisk(), saveToCloud()]).spread(function (disk: any, cloud: any) { - console.log("saved to disk:", disk.state === "fulfilled"); - console.log("saved to cloud:", cloud.state === "fulfilled"); - if (disk.state === "fulfilled") { - console.log("value was " + disk.value); - } - else if (disk.state === "rejected") { - console.log("rejected because " + disk.reason); - } +declare function saveToCloud(): Q.Promise; + +Q.allSettled([saveToDisk(), saveToCloud()]).spread((disk: any, cloud: any) => { + console.log("saved to disk:", disk.state === "fulfilled"); + console.log("saved to cloud:", cloud.state === "fulfilled"); + + if (disk.state === "fulfilled") { + console.log("value was " + disk.value); + } else if (disk.state === "rejected") { + console.log("rejected because " + disk.reason); + } }).done(); -var nodeStyle = (input: string, cb: Function) => { - cb(null, input); +const nodeStyle = (input: string, cb: (error: any, success: any) => void) => { + cb(null, input); }; -Q.nfapply(nodeStyle, ["foo"]).done((result: string) => {}); -Q.nfcall(nodeStyle, "foo").done((result: string) => {}); -Q.denodeify(nodeStyle)('foo').done((result: string) => {}); -Q.nfbind(nodeStyle)('foo').done((result: string) => {}); - +Q.nfapply(nodeStyle, ["foo"]).done((result: string) => { +}); +Q.nfcall(nodeStyle, "foo").done((result: string) => { +}); +Q.denodeify(nodeStyle)('foo').done((result: string) => { +}); +Q.nfbind(nodeStyle)('foo').done((result: string) => { +}); class Repo { - private items: any[] = [ - { name: 'Max', cute: false }, - { name: 'Annie', cute: true } - ]; + private items: any[] = [ + {name: 'Max', cute: false}, + {name: 'Annie', cute: true} + ]; - find(options: any): Q.Promise { - var result = this.items; + find(options: any): Q.Promise { + let result = this.items; - for (var key in options) { - result = result.filter(i => i[key] == options[key]); - } + for (let key in options) { + result = result.filter(i => i[key] === options[key]); + } - return Q(result); - } + return Q(result); + } } -var kitty = new Repo(); -Q.nbind(kitty.find, kitty)({ cute: true }).done((kitties: any[]) => {}); +const kitty = new Repo(); +Q.nbind(kitty.find, kitty)({cute: true}).done((kitties: any[]) => { +}); - -/* +/** * Test: Can "rethrow" rejected promises */ namespace TestCanRethrowRejectedPromises { + interface Foo { + a: number; + } - interface Foo { - a: number; - } + function nestedBar(): Q.Promise { + let deferred = Q.defer(); - function nestedBar(): Q.Promise { - var deferred = Q.defer(); + return deferred.promise; + } - return deferred.promise; - } + function bar(): Q.Promise { + return nestedBar() + .then((foo: Foo) => { + console.log("Lorem ipsum"); + }) + .fail((error) => { + console.log("Intermediate error handling"); - function bar(): Q.Promise { - return nestedBar() - .then((foo:Foo) => { - console.log("Lorem ipsum"); - }) - .fail((error) => { - console.log("Intermediate error handling"); - - /* - * Cannot do this, because: - * error TS2322: Type 'Promise' is not assignable to type 'Promise' - */ - //throw error; - - return Q.reject(error); - }) - ; - } - - bar() - .finally(() => { - console.log("Cleanup") - }) - .done() - ; + /* + * Cannot do this, because: + * error TS2322: Type 'Promise' is not assignable to type 'Promise' + */ + return Q.reject(error); + }); + } + bar() + .finally(() => { + console.log("Cleanup"); + }) + .done(); } // test Q.Promise.all -var y1 = Q().then(() => { - var s = Q("hello"); - var n = Q(1); - return <[typeof s, typeof n]>[s, n]; +const y1 = Q().then(() => { + let s = Q("hello"); + let n = Q(1); + return <[typeof s, typeof n]> [s, n]; }); -var y2 = Q().then(() => { - var s = "hello"; - var n = Q(1); - return <[typeof s, typeof n]>[s, n]; +const y2 = Q().then(() => { + let s = "hello"; + let n = Q(1); + return <[typeof s, typeof n]> [s, n]; }); -var p2: Q.Promise<[string, number]> = y1.then(val => Q.all(val)); -var p3: Q.Promise<[string, number]> = Q.all(y1); -var p5: Q.Promise<[string, number]> = y2.then(val => Q.all(val)); -var p6: Q.Promise<[string, number]> = Q.all(y2); +const p2: Q.Promise<[string, number]> = y1.then(val => Q.all(val)); +const p3: Q.Promise<[string, number]> = Q.all(y1); +const p5: Q.Promise<[string, number]> = y2.then(val => Q.all(val)); +const p6: Q.Promise<[string, number]> = Q.all(y2); - -Q.try(function () { - if (Math.random() % 2) { - throw new Error("The cloud is down!"); - } - return true; +Q.try(() => { + if (Math.random() % 2) { + throw new Error("The cloud is down!"); + } + return true; }) -.catch(function (error) { - console.error("Couldn't sync to the cloud", error); -}); + .catch((error) => console.error("Couldn't sync to the cloud", error)); diff --git a/types/q/tsconfig.json b/types/q/tsconfig.json index ec30c7c1c5..12c105d622 100644 --- a/types/q/tsconfig.json +++ b/types/q/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "q-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/q/tslint.json b/types/q/tslint.json new file mode 100644 index 0000000000..f4bf4b2db5 --- /dev/null +++ b/types/q/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "prefer-declare-function": false, + "strict-export-declare-modifiers": false, + "unified-signatures": false + } +}