您的位置:首页 > Web前端

[CoffeeScript]使用Yield功能

2016-04-13 06:16 344 查看
CoffeeScript 1.9 开始提供了类似ES6的yield关键字。 自己结合co和bluebird做了个试验。

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

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

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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: