Question

New to q, I got a sample code as follow, what it does is, get an order, then get the owner of the order, append the name of the owner to the order so that the complete order can be displayed, how to change this to using Q (kriskowal/q)? Thanks,

db.get_order(order_id, function(err, order) {
users.get_user(order.user_id, function(err, user) {
    order['$user_name'] = user.name
    console.log(order)
  })
})
Was it helpful?

Solution

I am assuming that get_order function depends on the db object and also get_user depends on user object. If that is the case, then you need to invoke those methods with Q.ninvoke, like this

Q.ninvoke(db, "get_order", order_id)
.then(function(order) {
    return Q.ninvoke(user, "get_user", order.user_id);
})
.then(function(user) {
    console.log(user.name);
})
.catch(function(err) {
    console.error(err);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top