[CoffeeScript]使用Yield功能

CoffeeScript 1.9 開始提供了相似ES6的yield關鍵字。 本身結合co和bluebird作了個試驗。npm

co -- http://npmjs.org/package/co  -- for generatorui

bluebird -- https://www.npmjs.com/package/bluebird  for Promisespa

co = require 'co'
Promise = require 'bluebird'

msg = "good"
func1 = () ->
  new Promise((resolve)->
    setTimeout(
      ()->
        console.log "func1"
        resolve({a:10,b:2})
    , 1000))


func2 = (opts) ->
  {a,b}= opts
  new Promise((resolve, reject)->
    setTimeout(()->
      console.log "func2", a, b
      console.log msg
      resolve(a * b * 2)
    , 1000)
  )

func3 = (r)->
  new Promise((resolve)->
    console.log "the result is #{r}"
    resolve()
  )
func4 = ()->
  new Promise (resolve)->
    console.log "done"
    resolve()

calc1= (r) ->
  yield func3(r)
  yield func4()

calc = ()->
  opts = yield func1()
  r = yield func2(opts)
  yield calc1(r)
#  yield func3(r)
#  yield func4()


co(calc) 
相關文章
相關標籤/搜索