This file contains hidden or 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 | |
| } | |
| } | |
| } | |
| } |