10th Sat
Swift2's defer for CoffeeScript
Though currently I am prefer to use CofferScript than Swift, I have thought that the defer of Swift2 is pretty cool. So I wrote a snippet that accomplishes the feature by using yield as like the manner of co is doing.
ruby>>
defer = (g) ->
deferred = []
go = (i) ->
{value,done} = do i.next
unless done
deferred.push value
go i
exit = ->
do f for f in deferred
process.removeListener 'exit', exit
process.on 'exit', exit
try go do g
catch then do exit
foo = (type) -> defer ->
console.log "#{type} 1"
yield -> console.log "#{type} deferred 1!"
yield -> console.log "#{type} deferred 2!"
console.log "#{type} 2"
if type == "exit" then do process.exit
else throw "throw"
console.log "3"
foo "throw"
foo "exit"
RESULTS
throw 1
throw 2
throw deferred 1!
throw deferred 2!
exit 1
exit 2
exit deferred 1!
exit deferred 2!
<<--
posted by
genki on Sat 10 Oct 2015 at 00:25 with 0 comments