-
-
Save b2whats/5e732a0cac20c4df36941050742b3cce 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
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( | |
response => response.text() | |
).then( | |
text => { | |
pending.delete(url); | |
cache.set(url, text); | |
} | |
); | |
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 = JSON.parse(fetchTextSync('/users/' + id)); | |
return user.name; | |
} | |
function getGreeting(name) { | |
if (name === 'Seb') { | |
return 'Hey'; | |
} | |
return fetchTextSync('/greeting'); | |
} | |
function getMessage() { | |
let name = getUserName(123); | |
return getGreeting(name) + ', ' + name + '!'; | |
} | |
runPureTask(getMessage).then(message => console.log(message)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment