Skip to content

Instantly share code, notes, and snippets.

@idibidiart
Forked from sebmarkbage/Infrastructure.js
Last active September 10, 2020 00:53
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save idibidiart/69fd5f9df339b5ef1783e6a8fae9fa51 to your computer and use it in GitHub Desktop.
Save idibidiart/69fd5f9df339b5ef1783e6a8fae9fa51 to your computer and use it in GitHub Desktop.
SynchronousAsync.js
const fetch = (url) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(url)
switch(url.match(/\d[aA-zZ]$/)[0]) {
case "1a":
resolve({name: "Seb"})
// or try this instead:
// reject({error: "something went wrong while fetching " + url})
break;
case "1b":
resolve({name: "Markbage"})
}
}, 1000)
})
}
let cache = new Map();
let pending = new Map();
function fetchTextSync(url) {
if (cache.has(url)) {
return cache.get(url);
}
if (pending.has(url)) {
throw pending.get(url);
}
let promise = fetch(url).then(
obj => {
pending.delete(url);
cache.set(url, obj);
},
error => {
pending.delete(url);
throw error
}
)
pending.set(url, promise);
throw promise;
}
async function runPureTask(task) {
for (;;) {
try {
return task();
} catch (x) {
if (x instanceof Promise) {
await x;
} else {
throw x
}
}
}
}
function getUserName(id) {
var user = fetchTextSync('/users/' + id)
return user.name;
}
function getGreeting(name) {
if (name === 'Seb Markbage') {
return 'Hey';
}
return 'Hello';
}
function getMessage() {
let firstName = getUserName('1a')
let lastName = getUserName('1b')
let name = firstName + ' ' + lastName
return getGreeting(name) + ', ' + name + '!';
}
runPureTask(getMessage).then(message => console.log(message), errMsg => console.log(errMsg.error));
@idibidiart
Copy link
Author

idibidiart commented Dec 17, 2017

This is a fork of @sebmarkbage 's genius "Poor Man's Algebraic Effects"

I added promise rejection scenario (see "try this" comment) and composition of fetchTextSync:

I like how I can compose idiomatically with this, e.g.: let result = fetchSync('/test/1a') + ' ' + fetchSync('/test/1b')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment