【问题标题】:Promisify async waterfall callback method possible?Promisify异步瀑布回调方法可能吗?
【发布时间】:2016-01-13 17:47:18
【问题描述】:

我在 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 模块还是重言式?

解决方案

像这样用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
    )

现在实例化的类方法是thenable和catchable,其实这些都是可用的:

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

【问题讨论】:

  • 您想将所有代码转换为一个promise,还是只想返回一个promise?如果稍后,您可以使用return new Promise(function(resolve, reject) { ... async.waterfall}),并在完成回调中调用resove(res)
  • 是的,我已经想通了……更新了代码。

标签: node.js asynchronous coffeescript


【解决方案1】:

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

你在顶部返回它:

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

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

【讨论】:

  • 确定已更改标签。 JS只是转译的CS,更难阅读,两者齐头并进我不再区分它们,抱歉造成混乱。您的解决方案是否可行,例如then 和 catch 现在是否隐含且可用?
  • Iced CS 很漂亮。感谢那。如果现在使用.then,它会在我的测试中超时..
  • 在我的if err-reject 块中有一个守卫阻止了解析。现在所有问题都解决了,完美。谢谢!
  • 你是说 Iced CoffeeScript 是 Promisfiying with Bluebird 过时了吗?
  • 问题是 IcedCoffeeScript 甚至在 Promise 流行之前就已经存在多年了,而且还有另一个 ToffeeScript(最终 JS 可能看起来像 ToffeeScript async ! 语法),以及另一个带有回呼和函数式编程的 LiveScript。 . 这些都比标准 JS 好,但是现在 ES6 非常流行,ES7 也不是那么糟糕,所以你可以考虑使用 ES7 和 babel,大多数人都在这样做。不管你喜欢什么,这些天我使用带有 babel 的 ES7,因为人们接受它,但出于某种原因通常不喜欢其他的,即使它们更好。
猜你喜欢
  • 2017-08-03
  • 1970-01-01
  • 2017-03-02
  • 1970-01-01
  • 2017-04-26
  • 2019-01-02
  • 2020-10-13
  • 1970-01-01
  • 2014-11-16
相关资源
最近更新 更多