After publishing https://xnim.me/blog/promises-and-gc I got some questions. One of them was how we can define current promise state?
It's quite simple with resolve
and reject
states, but it could be a little bit tricky for the pending
state. However, we have Promise.race
that is quite handy in this way:
const pending = {
state: "pending"
};
function getPromiseState(promise) {
return Promise.race([promise, pending]).then(
(value) => {
if (value === pending) {
return value;
}
return {
state: "resolved",
value
};
},
(reason) => ({ state: "rejected", reason })
);
}
Usage:
(async function () {
let result = await getPromiseState(Promise.resolve("resolved hello world"));
console.log(result);
result = await getPromiseState(Promise.reject("rejected hello world"));
console.log(result);
result = await getPromiseState(new Promise(() => {}));
console.log(result);
result = await getPromiseState("Hello world");
console.log(result);
})();
Example: https://codesandbox.io/s/restless-sun-njun1?file=/src/index.js