2015-10-15 55 views
0

我在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 callerasync 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) { ... }) 
+1

您想將所有代碼轉換爲承諾,還是隻想返回承諾?如果它稍後,你可以使用'return new Promise(function(resolve,reject){... async.waterfall})',並在完成的回調中調用resove(res)'。 – fuyushimoya

+0

是的我已經計算出...更新的代碼。 – nottinhill

回答

1

很確定這是coffeescript,你把它放在javascript標籤中。

您在頂部返回它:

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

還應考慮IcedCoffeeScript和ES7異步/ AWAIT。

+0

確定已更改標籤。 JS只是編譯了CS,而且很難閱讀,兩者並行,我不再區分它們,抱歉造成了混淆。您的解決方案是否可行,例如那麼現在趕上並暗示和可用? – nottinhill

+0

冰冰CS很漂亮。感謝那。如果現在使用'.then',它會在我的測試中超時.. – nottinhill

+0

在我的'if err'-reject block中有一個警衛阻止瞭解析。現在所有問題都消失了,它的完美性謝謝! – nottinhill