@marius said in Need help with Promises:
What am I missing?
Hi Marius.
Nice work! It’ll be easier to collaborate on this if you set up a github project for this.
Looking at your code there is just a minor, but important thing missing. While you can omit brackets with function calls which include parameters you cannot do so without parameters, i.e you need to write reject()
and resolve()
as just writing reject
, for example, will return the function without calling it at this point. Same applies for your getRob() method. For the reject case my suggestion is to pass the error along, so that you handle it eventually later on. At the point where you invoke connect()
you should also have a catch block as otherwise you may see unhandled exceptions if the authorization fails for some reason.
Note beyond, it is also possible to automatically promisify callback interfaces, like node-kobold. See http://bluebirdjs.com/docs/api/promisification.html for info.
connect: () =>
return new Promise( (resolve, reject) =>
@client.authorize(@config.email, @config.password, false, (error) ->
if error
env.logger.warn error
reject(error)
else
env.logger.info("successfully connected to robot")
resolve()
)
)
getRob: () =>
env.logger.info("getrob 0")
return new Promise( (resolve, reject) =>
env.logger.info("getrob 1")
@client.getRobots( (error, robots) =>
env.logger.info("getrob 2")
if error
env.logger.warn error
reject(error)
else
env.logger.info("getrob 3")
if robots.length
@robot = robots[@config.robotno]
env.logger.info("robot selected")
resolve()
else
env.logger.warn "no robot found"
reject(new Error("no robot found")
)
)
constructor: (@config) ->
@name = @config.name
@id = @config.id
@client = new libKobold.Client()
@connect().then( () =>
env.logger.warn "connected"
)
.catch( (error) =>
env.logger.error '' + error
)
"It always takes longer than you expect, even when you take into account Hofstadter's Law.", Hofstadter's Law