我在node.js中這樣的代碼:Promisify異步瀑布回調方法可能嗎?
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
回調?如何promisify async
模塊或這是重複?
解決方案
Promisify類方法與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和開捕,其實這些都是可供選擇:
promise
.then(okFn, errFn)
.spread(okFn, errFn) //*
.catch(errFn)
.catch(TypeError, errFn) //*
.finally(fn) //*
.map(function (e) { ... })
.each(function (e) { ... })
您想將所有代碼轉換爲承諾,還是隻想返回承諾?如果它稍後,你可以使用'return new Promise(function(resolve,reject){... async.waterfall})',並在完成的回調中調用resove(res)'。 – fuyushimoya
是的我已經計算出...更新的代碼。 – nottinhill