Skip to content

Instantly share code, notes, and snippets.

@antenando
Forked from idibidiart/Infrastructure.js
Created December 30, 2017 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antenando/f0df8c603d955d31e7c59cf7f891c2ca to your computer and use it in GitHub Desktop.
Save antenando/f0df8c603d955d31e7c59cf7f891c2ca 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));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment