smartpromise/ts/index.ts

80 lines
1.8 KiB
TypeScript
Raw Normal View History

2017-01-17 14:28:28 +00:00
export interface IResolve<T> {
2019-09-11 13:38:37 +00:00
(value?: T | PromiseLike<T>): void;
2017-01-17 14:28:28 +00:00
}
export interface IReject {
2018-03-16 09:24:12 +00:00
(reason?: any): void;
2017-01-17 14:28:28 +00:00
}
2018-03-16 09:24:12 +00:00
export type TDeferredStatus = 'pending' | 'fulfilled' | 'rejected';
2017-01-17 14:28:28 +00:00
export class Deferred<T> {
2019-09-11 13:37:17 +00:00
public promise: Promise<T>;
public resolve: IResolve<T>;
public reject: IReject;
public status: TDeferredStatus;
public startedAt: number;
public stoppedAt: number;
public get duration(): number {
if (this.stoppedAt) {
return this.stoppedAt - this.startedAt;
} else {
return Date.now() - this.startedAt;
}
}
2018-03-16 09:24:12 +00:00
constructor() {
2017-07-06 12:10:18 +00:00
this.promise = new Promise<T>((resolve, reject) => {
2019-09-11 13:37:17 +00:00
this.resolve = (valueArg: T | PromiseLike<T>) => {
this.status = 'fulfilled';
this.stoppedAt = Date.now();
resolve(valueArg);
};
this.reject = (reason: any) => {
this.status = 'rejected';
this.stoppedAt = Date.now();
reject(reason);
};
this.startedAt = Date.now();
2018-03-16 09:24:12 +00:00
this.status = 'pending';
});
2017-07-06 12:10:18 +00:00
}
2017-01-17 14:28:28 +00:00
}
export let defer = <T>() => {
2018-03-16 09:24:12 +00:00
return new Deferred<T>();
};
2017-01-17 14:28:28 +00:00
/**
* Creates a new resolved promise for the provided value.
*/
2017-01-20 23:45:11 +00:00
export let resolvedPromise = <T>(value?: T): Promise<T> => {
2018-03-16 09:24:12 +00:00
return Promise.resolve(value);
};
/**
* Creates a new rejected promise for the provided reason.
*/
2018-03-16 09:24:12 +00:00
export let rejectedPromise = err => {
return Promise.reject(err);
};
2017-01-28 15:37:54 +00:00
interface IAsyncFunction<T> {
2019-03-26 11:07:12 +00:00
(someArg: T): Promise<T>;
}
2017-07-06 12:55:42 +00:00
2019-03-26 11:07:12 +00:00
export let map = async <T>(inputArg: T[], functionArg: IAsyncFunction<T>) => {
2018-03-16 09:24:12 +00:00
let promiseArray: Promise<any>[] = [];
let resultArray = [];
2017-07-06 12:10:18 +00:00
for (let item of inputArg) {
let promise: Promise<any> = functionArg(item);
2018-03-16 09:24:12 +00:00
promiseArray.push(promise);
2017-07-06 12:10:18 +00:00
promise.then(x => {
2018-03-16 09:24:12 +00:00
resultArray.push(x);
});
2017-07-06 12:10:18 +00:00
}
2018-03-16 09:24:12 +00:00
await Promise.all(promiseArray);
return resultArray;
};