【发布时间】: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