I'm trying to wrap my head around the Q library/promises in general so I can implement it in my node application, but I'm having trouble finding something concise and specific enough to quickly get started.
Could someone help me translate this code into an asycronous pattern using Q's promise library?
// # For those new to coffeescript
// # '(params) ->' === 'function (params) {}' in coffeescript
// # '@' === 'this' in coffeescript
// # NPM
Q = require 'q'
// # Database class
module.exports = class Database
constructor: () ->
// # mongoose
@mongoose = require('mongoose')
// # Make database connection
@connect_database()
connect_database: () ->
try
@mongoose.connect('mongodb://127.0.0.1:27017/database')
return 'Database connected'.green
catch e
return ('Database connection error: ' + e.toString()).red
Once I see something directly applicable I think it will be much easier for me to convert the rest of my application to this pattern.
So basically you want to return the dfd.promise and then resolve or reject it after connecting to the DB.
Q = require 'q'
connect: () ->
# Create deferred object
dfd = Q.defer()
# Attempt to connect
try
@mongoose.connect(...)
# Resolve deferred object
dfd.resolve('Database connected')
catch e
# Reject deferred with error object
dfd.reject(e)
# Return promise immediately
dfd.promise
Now when you run the connect method, you will get a promise object that you can bind to the .then and .fail methods
db.connect()
.then(msg) ->
.fail(e) ->