-
-
Save idibidiart/69fd5f9df339b5ef1783e6a8fae9fa51 to your computer and use it in GitHub Desktop.
SynchronousAsync.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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')