Created
April 23, 2020 02:30
-
-
Save Lucifier129/708f17339b1fd52fb9d01110a7e895a0 to your computer and use it in GitHub Desktop.
poor man's algebraic-effects via throw + hand-written continuations
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 run = (f, handlers) => { | |
try { | |
return f(); | |
} catch (effect) { | |
if (effect.type in handlers) { | |
handlers[effect.type](effect.payload, effect.continuation); | |
} else { | |
throw effect | |
} | |
} | |
}; | |
let async = (f) => (...args) => { | |
let handlers = { | |
await(fetcher, k) { | |
fetcher(async(k)) | |
}, | |
}; | |
run(() => f(...args), handlers); | |
}; | |
let await = (fetcher) => (next) => { | |
throw { | |
type: "await", | |
payload: fetcher, | |
continuation: next, | |
}; | |
}; | |
let db = { | |
a: { | |
data: "a", | |
}, | |
b: { | |
data: "b", | |
}, | |
}; | |
let fetchAllData = () => k => { | |
setTimeout(() => { | |
Object.values(db).forEach(k) | |
}, 100) | |
} | |
let testMultShot = async(() => { | |
await(fetchAllData()) | |
(data => { | |
console.log('multi-shot', data) | |
}) | |
}) | |
let fetchData = (id) => (k) => { | |
setTimeout(() => { | |
k(db[id]); | |
}, 100); | |
}; | |
let main = async((id) => { | |
await(fetchData(id)) | |
(data => { | |
console.log("data", data); | |
}); | |
}); | |
let test = async(() => { | |
await(fetchData('a')) | |
(a => { | |
console.log('a', a) | |
await(fetchData('b')) | |
(b => { | |
console.log('b', b) | |
await(fetchData('a')) | |
(c => { | |
console.log('c', c) | |
}) | |
}) | |
}) | |
}) | |
main('a') | |
main('b') | |
test() | |
testMultShot() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
RoundRobinScheduler