Created
October 10, 2013 08:48
-
-
Save refractalize/6915157 to your computer and use it in GitHub Desktop.
How to make functions both synchronous and asynchronous at the same time. The caller decides.
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
function (f) is asynchronous = | |
r/function(.*continuation)/.test (f.to string ()) | |
ensure (b) is asynchronous = | |
if (function (b) is asynchronous) | |
b | |
else | |
@(args, ..., cont) | |
try | |
cont (nil, b (args, ...)) | |
catch (e) | |
cont (e) | |
(c) or default continuation = | |
c @or @(error, result) | |
if (error) | |
throw (error) | |
else | |
result | |
f (a, cont) = | |
cont := (cont) or default continuation | |
g (a) @(error, result) | |
cont (nil, 'this is f ' + result) | |
g (a, cont) = | |
cont := (cont) or default continuation | |
cont (nil, a + '!') | |
h (b, cont) = | |
cont := (cont) or default continuation | |
(ensure (b) is asynchronous) @(error, result) | |
cont (nil, 'this calls a block that is ' + result) | |
i (b, cont) = | |
cont := (cont) or default continuation | |
set timeout @{ | |
(ensure (b) is asynchronous) @(error, result) | |
cont (error, result) | |
} 1000 | |
console.log (f 'not being called asynchronously') | |
console.log (f 'being called asynchronously'!) | |
console.log ( | |
h | |
'not async' | |
) | |
console.log ( | |
h! | |
'async' | |
) | |
i | |
console.log 'this was called, round 1' | |
console.log 'finished round 1' | |
i! | |
console.log 'this was called, round 2' | |
console.log 'finished round 2' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment