【问题标题】:Promisfy CoffeeScript Class承诺 CoffeeScript 类
【发布时间】:2015-10-21 23:12:17
【问题描述】:

我有这样的 CoffeeScripted 类:

class Hair
  truncate: () ->
    DoAsyncStuffWithMyDB ->
      console.log "Async Stuff With My DB completed"

现在我想使用这个类,例如:

doghair = new Hair
doghair
.truncate()
.then(() ->
    #do stuff
)

我如何使用 Bluebird 做到这一点?

【问题讨论】:

  • DoAsyncStuffWithMyDB 是否已经返回了一个承诺?如果不是,您需要 [promisify](stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises) 它
  • DoAynscStuffWithMyDB() 接受哪些参数?要承诺某事,需要知道它需要什么论据。如果它遵循 node.js 异步调用约定,那么您可以使用 Bluebird 的 promisify() 函数。如果没有,您必须制作自定义包装器以返回正确解析的承诺。

标签: node.js promise bluebird


【解决方案1】:

这是自定义的实现方式:

Promise  = require('bluebird')
class Hair
  truncate: () ->
    new Promise((resolve, reject) ->
      DoAsyncStuffWithMyDB.create data, (err,res) ->
        if err
          reject err
        else
          resolve true
    )

现在你的实例化对象是then-able。恭喜!

【讨论】:

    猜你喜欢
    • 2013-09-28
    • 2015-12-10
    • 2012-09-22
    • 2011-06-04
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 2018-06-23
    相关资源
    最近更新 更多