Skip to content

Instantly share code, notes, and snippets.

@XoseLluis
Created September 8, 2020 20:31
Show Gist options
  • Save XoseLluis/d280d75b466dc3b233f41d36dace4976 to your computer and use it in GitHub Desktop.
Save XoseLluis/d280d75b466dc3b233f41d36dace4976 to your computer and use it in GitHub Desktop.
Another way to implement Synchronous Inspection for Promises (as the one provided by bluebird) Not using Inheritance this time, just a new Promise chained to the original one.
//returns a new Promise expanded with inspection methods
function enableSyncInspect(pr){
//we trap these variables in the closure making them sort of private, and allow public access only through the inspection methods that we add to the new promise
let isFulfilled = false;
let value = null; //resolution result
let isRejected = false;
let reason = null; //rejection reason
let isPending = true;
//create a new promise that gets resolved-rejected by the original promise and gets expanded with inspection methods
let prWrapper = pr.then(_value => {
isPending = false;
isFulfilled = true;
value = _value;
return _value;
}, _reason => {
isPending = false;
isRejected = true;
reason = _reason;
return _reason;
});
prWrapper.isFulfilled = () => {
return isFulfilled;
}
prWrapper.getValue = () => {
return isFulfilled
? value
: (() => {throw new Error("Unfulfilled Promise");})(); //emulate "throw expressions"
}
prWrapper.isRejected = () => {
return isRejected;
}
prWrapper.getReason = () => {
return isRejected
? reason
: (() => {throw new Error("Unrejected Promise");})(); //emulate "throw expressions"
}
prWrapper.isPending = () => {
return isPending;
}
return prWrapper;
}
function formatAsync(msg){
return new Promise((resFn, rejFn) => {
console.log("starting format");
setTimeout(() => {
console.log("finishing format");
resFn(`[[${msg}]]`);
}, 2000);
});
}
function printValueIfFulfilled(pr){
if (pr.isFulfilled()){
console.log("Promise resolved to: " + pr.getValue());
}
else{
console.log("Promise NOT resolved yet");
}
}
//async main
(async () => {
let pr1 = formatAsync("Bonjour");
let syncInspectPr = enableSyncInspect(pr1);
console.log("isPending: " + syncInspectPr.isPending());
//this fn runs in 1 seconds (while the async fn takes 3 seconds) so it won't be fulfilled at that point)
setTimeout(() => printValueIfFulfilled(syncInspectPr), 1000);
let result = await syncInspectPr;
console.log("result value: " + result);
printValueIfFulfilled(syncInspectPr);
})();
//Output:
// starting format
// isPending: true
// Promise NOT resolved yet
// finishing format
// result value: [[Bonjour]]
// Promise resolved to: [[Bonjour]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment