Skip to content

Instantly share code, notes, and snippets.

@dduleone
Last active January 11, 2019 19:58
Show Gist options
  • Save dduleone/821bdb02d3fbf48bcbe96a59c737b3aa to your computer and use it in GitHub Desktop.
Save dduleone/821bdb02d3fbf48bcbe96a59c737b3aa to your computer and use it in GitHub Desktop.
Thoughts on Async APIs
/* Async Dependency */
const doIt = () => {
console.log('resolved');
};
/* Wrapper to Support Blocking */
const doItAndThenLater = (andThenDoThis) => {
const callback = (typeof andThenDoThis === "function") ? andThenDoThis : (result) => {return result};
setTimeout(() => {
doIt();
callback();
}, 2000);
return;
};
/* Three approaches:
I expect:
doItAndPromise(),
doItAndWait(),
doItAndForgetIt()
would be what our wrapper API should support...
And:
agnosticFunctionStillNeedsToBeAsync()
agnosticFunctionRequiringBlocking()
agnosticFunction()
represent implementation code that can use whatever method is appropriate.
*/
/* These would be used when a Promise that can be resolved is desirable. */
const doItAndPromise = () => {
return new Promise((callback) => {
doItAndThenLater(callback);
});
};
const agnosticFunctionStillNeedsToBeAsync = async () => {
console.log('calling');
console.log(await doItAndPromise()); // expected output: 'resolved'
};
/* These would be used when blocking is specifically required. */
const doItAndWait = async () => {
return await doItAndPromise();
};
const agnosticFunctionRequiringBlocking = () => {
console.log('calling');
console.log(doItAndWait()); // expected output: 'resolved'
};
/* These would be used for a naive implementation that does not care about blocking. */
const doItAndForgetIt = () => {
doItAndThenLater(undefined);
};
const agnosticFunction = () => {
console.log('calling');
console.log(doItAndForgetIt()); // expected output: 'resolved'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment