如何调用另一个函数内的函数(nodejs,mysql)

时间:2018-05-15 13:11:25

标签: mysql node.js

我需要调用一个函数并返回结果,但它不会返回结果。经过一些搜索,我知道必须用承诺来完成。以下是代码,我想知道如何使用承诺返回结果。

var payment = {
paymentDetails: function(data){
    var  order_id = data.order_id;

    db.query("select o.sku,p.published_on,sp.total_sale_price as amount, o.total_cost from orders o left join product p on p.sku = o.sku and p.is_published = 1 and p.is_deleted = 0 left join supplier_product sp on sp.product_id = p.product_id and sp.is_deleted = 0 and sp.active = 1 where o.order_id = ? and o.order_status < 13",[order_id], function(err, res){
        if(err) return err;

        var order_details = res[0];
        var payment_details  = module.exports.getPaymentDetails(order_id);
    });

},

getPaymentDetails: function(order_id){
    db.query("select payment_type, amount, status from payment_details where payment_mode = 5 and invoice_type = 8 and status in ('success','pending_for_approval') and merchant_order_id = ?",[order_id], function(err, res){
      if(err){ 
        throw err;
      } else {
        return res;
      }          
  });  
} 
};
module.exports = payment;

1 个答案:

答案 0 :(得分:1)

基于回调的方法。

var payment = {
    paymentDetails: function(data, callback){
        var  order_id = data.order_id;

        db.query("somequery",[order_id], function(err, res){
           if(err) return callback(err, null);

           var order_details = res[0];
           var payment_details = module.exports.getPaymentDetails(order_id, callback);
        });

    },

    getPaymentDetails: function(order_id, callback){
         db.query("somequert",[order_id], function(err, res){
            if(err){ 
               return callback(err, null);
            } else {
               return callback(null, res);
            }          
         });  
    } 
};

module.exports = payment;

现在,您可以像以下一样使用它

payment.paymentDetails({order_id: 1}, function(err, details){ 
   // some code 
});