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)
  })
})
有帮助吗?

解决方案

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);
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top