Node-Fibers Example

With node-fibers, we can write codes in traditionally synchronous fashion and avoid deep nested callback calls without blocking the Node event loop.

Below is an example to generate Fibonacci series. Each run resumes the calculation loop and returns a number to the calling code.

  1 Fiber = require 'fibers'
  2
  3 Fibonacci = ->
  4   return Fiber(->
  5     Fiber.yield 0
  6     prev = 0
  7     curr = 1
  8     while true
  9       Fiber.yield curr
 10       tmp = prev + curr
 11       prev = curr
 12       curr = tmp
 13   )
 14
 15 seq  = Fibonacci()
 16 i = 0
 17 while i < 100
 18   i = seq.run()
 19   console.log i
 20 #coffee fibonacci.coffee
 21 #0
 22 #1
 23 #1
 24 #2
 25 #3
 26 #5
 27 #8
 28 #13
 29 #21
 30 #34
 31 #55
 32 #89
 33 #144

About rp8

Specialized in building sophisticated systems for trading & risks in commodity, exotics, commodity index & structured products. Specially interested in using open source stacks and cloud computing to build new generation of services and apps. Enjoy mountain biking & photography. github
This entry was posted in JavaScript, Node.js and tagged , . Bookmark the permalink.