2015-10-02 62 views
-1

我有這樣的CoffeeScripted類:Promisfy CoffeeScript的類

class Hair 
    truncate:() -> 
    DoAsyncStuffWithMyDB -> 
     console.log "Async Stuff With My DB completed" 

現在我想使用這個類,例如:

doghair = new Hair 
doghair 
.truncate() 
.then(() -> 
    #do stuff 
) 

如何使用藍鳥也達到這樣的?

+0

DoAsyncStuffWithMyDB是否已經返回承諾?如果它不是你需要[promisify](stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises)它 –

+0

'DoAynscStuffWithMyDB()'採取什麼參數?爲了促成某些事情,人們需要知道它需要什麼論點。如果它遵循node.js異步調用約定,那麼您可以使用Bluebird的'promisify()'函數。如果沒有,你必須做一個自定義包裝來返回已經正確解析的承諾。 – jfriend00

回答

0

這是它是如何實現自定義的方式:

Promise = require('bluebird') 
class Hair 
    truncate:() -> 
    new Promise((resolve, reject) -> 
     DoAsyncStuffWithMyDB.create data, (err,res) -> 
     if err 
      reject err 
     else 
      resolve true 
    ) 

現在你實例化的對象是then -able。恭喜!