smartpromise/ts/index.ts

83 lines
2.0 KiB
TypeScript
Raw Normal View History

2023-04-04 18:22:57 +00:00
import { defer } from './smartpromise.classes.deferred.js';
2017-01-17 14:28:28 +00:00
2023-04-04 18:35:54 +00:00
export * from './smartpromise.classes.cumulativedeferred.js';
2023-04-04 18:22:57 +00:00
export * from './smartpromise.classes.deferred.js';
2017-01-17 14:28:28 +00:00
/**
* Creates a new resolved promise for the provided value.
*/
2020-10-15 18:02:14 +00:00
export const 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.
*/
2020-10-15 18:02:14 +00:00
export const rejectedPromise = (err) => {
2018-03-16 09:24:12 +00:00
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
2020-10-15 18:02:14 +00:00
/**
* accepts an array of inputs and a function that accepts the input.
* runs all items with the function and returns the result array when all items have run
* @param inputArg
* @param functionArg
*/
export const map = async <T>(inputArg: T[], functionArg: IAsyncFunction<T>) => {
const promiseArray: Promise<any>[] = [];
const resultArray = [];
for (const item of inputArg) {
const promise: Promise<any> = functionArg(item);
2018-03-16 09:24:12 +00:00
promiseArray.push(promise);
2020-10-15 18:02:14 +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;
};
2020-10-15 18:02:14 +00:00
2023-04-04 18:22:57 +00:00
export const timeoutWrap = async <T = any>(
promiseArg: Promise<T>,
timeoutInMsArg: number,
rejectArg = true
) => {
2020-10-16 02:06:50 +00:00
return new Promise<T>((resolve, reject) => {
2020-10-15 18:02:14 +00:00
setTimeout(() => {
2022-02-27 20:02:27 +00:00
if (rejectArg) {
reject(new Error('timeout'));
} else {
resolve(null);
}
}, timeoutInMsArg);
2020-10-16 01:39:19 +00:00
promiseArg.then(resolve, reject);
2020-10-15 18:02:14 +00:00
});
};
2021-04-23 17:58:37 +00:00
2023-04-04 18:22:57 +00:00
export const timeoutAndContinue = async <T = any>(
promiseArg: Promise<T>,
timeoutInMsArg = 60000
) => {
2022-02-27 20:02:27 +00:00
return timeoutWrap(promiseArg, timeoutInMsArg, false);
2023-04-04 18:22:57 +00:00
};
2022-02-27 20:02:27 +00:00
2021-04-23 17:58:37 +00:00
export const getFirstTrueOrFalse = async (promisesArg: Promise<boolean>[]) => {
2021-04-23 18:04:08 +00:00
const done = defer<boolean>();
2021-04-23 17:58:37 +00:00
for (const promiseArg of promisesArg) {
promiseArg.then((resultArg) => {
if (resultArg === true) {
done.resolve(true);
}
});
}
Promise.all(promisesArg).then(() => {
done.resolve(false);
});
return done.promise;
};