我在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!
)
现在如何return a Promise to the method caller
来自async waterfall
回调?如何宣传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
)
现在实例化的类方法是可用的和可捕获的,实际上所有这些都是可用的:
promise
.then(okFn, errFn)
.spread(okFn, errFn) //*
.catch(errFn)
.catch(TypeError, errFn) //*
.finally(fn) //*
.map(function (e) { ... })
.each(function (e) { ... })
答案 0 :(得分:1)
非常肯定这是coffeescript,你把它放在javascript标签中。
你将它返回顶部:
myMethod: () ->
return new Promise( (resolve, reject) ->
async.waterfall [
# ...
], (err, result) ->
if (err)
reject(err)
else
resolve(result)
)
另请参阅IcedCoffeeScript和ES7 async / await。