承诺异步瀑布回调方法可能



我在node.js中得到了这样的代码:

class MyClass
  myMethod: () ->
    async.waterfall [
      (next) ->
        # do async DB Stuff
        next null, res
      (res, next) ->
        # do other async DB Stuff
        next null, res
    ], (err, res) ->
        # return a Promise to the method Caller
myclass = new MyClass
myclass.myMethod()
       .then((res) ->
        # hurray!
       )
       .catch((err) ->
       # booh!
       )

现在如何从async waterfall回调return a Promise to the method caller ?如何承诺async模块或这是同义反复?

<

解决方案/strong>

bluebird类方法进行这样的承诺:

 class MyClass
   new Promise((resolve, reject) ->
      myMethod: () ->
        async.waterfall [
          (next) ->
            # do async DB Stuff
            next null, res
          (res, next) ->
            # do other async DB Stuff
            next null, res
        ], (err, res) ->
            if err 
              reject err
            else
              resolve res
    )

现在实例化的类方法是可启用和可捕获的,实际上所有这些都是可用的:

promise
  .then(okFn, errFn)
  .spread(okFn, errFn) //*
  .catch(errFn)
  .catch(TypeError, errFn) //*
  .finally(fn) //*
  .map(function (e) { ... })
  .each(function (e) { ... })

很确定这是coffeescript,你把它放在javascript标签中。

你在顶部返回它:

myMethod: () ->
  return new Promise( (resolve, reject) ->
    async.waterfall [
       # ...
    ], (err, result) ->
      if (err)
        reject(err)
      else
        resolve(result)
  )

还可以查看IcedCoffeeScript和ES7 async/await。

最新更新