 
 #=====================================================================
 
+# Makes a function run in its own fiber and returns a promise.
+$coroutine = (fn) ->
+  return (args...) ->
+    return new $Promise (resolve, reject) ->
+      $fiber(=>
+        try
+          resolve fn.apply this, args
+        catch error
+          reject error
+      ).run()
+      return
+
 # Makes a function running in its own fiber.
 $fiberize = (fn) ->
-  (args...) ->
+  return (args...) ->
     $fiber(=>
       try
         fn.apply this, args

    fiber.throwInto.bind fiber
  )

  $fiber.yield()

$wait.register = ->
  throw new Error 'something has already been registered' if $wait._stash

  deferred = $Promise.defer()
  $wait._stash = deferred.promise

  deferred.callback

#=====================================================================

module.exports = {
  $fiberize
  $coroutine
  $waitEvent
  $wait
}

  handler = (args...) ->
    emitter.removeListener 'error', errorHandler
    fiber.run args
    return
  errorHandler = (error) ->
    emitter.removeListener event, handler
    fiber.throwInto error
    return

  emitter.once event, handler
  emitter.once 'error', errorHandler

  return $fiber.yield()

# Waits for a promise or a continuable to end.
#
