Skip to content

Instantly share code, notes, and snippets.

@dzharii
Created July 20, 2020 23:33
Show Gist options
  • Save dzharii/782faf130a7a0f01b32d066ee2896d46 to your computer and use it in GitHub Desktop.
Save dzharii/782faf130a7a0f01b32d066ee2896d46 to your computer and use it in GitHub Desktop.
A way to query Typescript/JavaScript/NodeJS Promise state
/**
* The following doc describes one way how to path Promise to return it's state
* * https://stackoverflow.com/questions/21485545/is-there-a-way-to-tell-if-an-es6-promise-is-fulfilled-rejected-resolved
* * https://ourcodeworld.com/articles/read/317/how-to-check-if-a-javascript-promise-has-been-fulfilled-rejected-or-resolved
*
* I personally do not like monkey-path approach, on the one hand... and it simply
* does not work on the other hand.
*
* Solution that works for me is to make an explicit wrapper.
*
*/
class PromiseWrap<T> {
promise: Promise<T>
category: string;
fulfilled: boolean = false;
rejected: boolean = false;
constructor (promise: Promise<T>, category?: string) {
this.promise = promise;
this.category = category || '';
this.promise.then(
(value) => {
this.fulfilled = true;
},
(err) =>{
this.rejected = true;
}
)
}
isPending() {
return !(this.fulfilled || this.rejected)
}
isFulfilled() {
return this.fulfilled;
}
isRejected() {
return this.rejected;
}
getCategory() {
return this.category;
}
get(): Promise<T> {
return this.promise;
}
}
async function sleep(ms: number) {
const p = new Promise<void>((resolve, reject) => {
setTimeout(() => resolve(), ms);
});
return p;
}
(async function main() {
let tasks = [
new PromiseWrap(sleep(1000), 'Old Promise'),
new PromiseWrap(sleep(1500), 'Old Promise'),
new PromiseWrap(sleep(2000), 'Old Promise'),
new PromiseWrap(sleep(6000), 'Old Promise'),
new PromiseWrap(sleep(7000), 'Very Old Promise'),
];
for (let i = 0; i < 20; i++) {
console.clear();
console.log(tasks.map( (p, i) => {
return JSON.stringify({
index: i,
category: p.getCategory(),
fullfiled: p.isFulfilled(),
rejected: p.isRejected(),
pending: p.isPending(),
});
}));
if (i == 9 ) {
tasks = tasks.filter(t => t.isPending());
tasks.push(
new PromiseWrap(sleep(3000), 'New Promise'),
new PromiseWrap(sleep(2000), 'New Promise'),
new PromiseWrap(sleep(3000), 'New Promise'),
new PromiseWrap(sleep(6000), 'New Promise'),
);
}
await sleep(500);
}
await Promise.all(tasks.map(p => p.get()));
})().catch(err => {
console.error(err);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment