如果在节点js中使用mysql发生错误,如何在节点js中回滚函数

时间:2017-11-07 06:29:20

标签: javascript mysql node.js

如何组合这三个函数.compdb()和pardb()与动态数组一起使用。

function marketdb(sellwalletamount,custId,receivedamount){

    return new Promise(function(resolve, reject) {
        let sql1 = "SELECT * FROM pair_master WHERE id ='" + req.body.pair_id + "'";
        connection.query(sql1, function(error, pairdata) {
            if (error) {

                reject(error)
            } else {
                if (pairdata[0] == null || pairdata[0] == undefined) {

                    reject(error);
                } else {
                    let sql2 = "SELECT * FROM customer_wallet WHERE customer_id ='" + custId + "'AND currency_code='" + pairdata[0].to + "'";
                    connection.query(sql2, function(error, receivewalletdata) {
                        if (error) {

                            reject(error);
                        } else {

                            if (receivewalletdata[0] == null || receivewalletdata == undefined) {
                                console.log({ success: false, message: "received wallet not found" });
                                reject(error);
                            } else {


                                var addmoney = receivewalletdata[0].total_amount + receivedamount;

                                let sql3 = "UPDATE customer_wallet SET total_amount ='" + addmoney + "' WHERE customer_id='" + custId + "'AND currency_code='" + pairdata[0].to + "'";
                                connection.query(sql3, function(error, response) {
                                    if (error) {
                                        console.log({ success: false, message: "Error", error: error });
                                        reject(error);

                                    } else {
                                        var presentBalance = sellwalletamount - req.body.quantity;

                                        let sql4 = "UPDATE customer_wallet SET total_amount ='" + presentBalance + "' WHERE customer_id='" + custId + "'AND currency_code='" + pairdata[0].from + "'";

                                        connection.query(sql4, function(error, final) {
                                            if (error) {
                                                console.log({ success: false, message: "Error", error: error });
                                                reject(error);

                                            } else {


                                                let sql5 = "INSERT INTO transaction_master (status,trade_type,type,customer_id,avg_price,created_at) values ('Fully Executed','Sell','Market','" + custId + "','" + receivedamount + "','" + created_at + "');"

                                                connection.query(sql5, function(err, transmasterid) {
                                                    if (err) {
                                                        reject(error);

                                                    } else {

                                                        resolve(transmasterid.insertId) 
                                                    }
                                                })

                                            }
                                        })
                                    }
                                })
                            }
                        }
                    })
                }
            }
        })
    })
}




function compdb(dedd, mcustId, custtranmastId) {
    return new Promise(function(resolve, reject) {

        var i = dedd.length
        console.log("i in complte save", i)
        async.forEachOf(dedd, function(error, i, inner_callback) {
                let sql1 = "UPDATE buy SET status = 'Fully Executed' WHERE id ='" + dedd[i].trade_id + "'";
                console.log(sql1)
                connection.query(sql1, function(err, rows, fields) {
                    if (!err) {

                        console.log("done")
                        console.log(dedd.trade_id)
                        let sql = "Select*from transaction_master where trade_type ='Buy' and trade_id='" + dedd[i].trade_id + "'";
                        console.log(sql)
                        connection.query(sql, function(err, transactionmasterdata) {
                            if (err) {

                                inner_callback(err);
                            } else if (transactionmasterdata[0] == null || transactionmasterdata[0] == undefined) {
                                console.log(transactionmasterdata)
                                let sql2 = "INSERT INTO transaction_master (status,trade_type,type,trade_id,customer_id,avg_price,created_at) values ('Fully Executed','Buy','Limit','" + dedd[i].trade_id + "','" + dedd[i].customer_id + "','" + dedd[i].money + "','" + created_at + "');"

                                connection.query(sql2, function(err, results) {
                                    if (!err) {


                                        let sql4 = "INSERT INTO transaction (customer_id,trade_type,type,trade_id,to_from_customer_id,price,quantity,status,pair_id,created_at,transanction_master_id) values ('" + dedd[i].customer_id + "','Buy','Limit','" + dedd[i].trade_id + "','" + mcustId + "','" + dedd[i].money + "','" + dedd[i].quantity + "','Fully Executed','" + dedd[i].pair_id + "','" + created_at + "','" + results.insertId + "'),('" + mcustId + "','Sell','Market','" + dedd[i].trade_id + "','" + dedd[i].customer_id + "','" + dedd[i].money + "','" + dedd[i].quantity + "','Fully Executed','" + dedd[i].pair_id + "','" + created_at + "','" + custtranmastId + "');"

                                        connection.query(sql4, function(err, rows, fields) {
                                            if (!err) {


                                                inner_callback(null);
                                            } else {

                                                inner_callback(err);
                                            };
                                        });
                                    } else {

                                        inner_callback(err);
                                    }
                                })
                            } else {

                                var newavg_price = (transactionmasterdata[0].avg_price + dedd[i].money) / 2;

                                let sql2 = "UPDATE transaction_master SET status='Fully Executed',avg_price='" + newavg_price + "' where id= '" + transactionmasterdata[0].id + "'";

                                connection.query(sql2, function(err, results) {
                                    if (!err) {


                                        let sql4 = "INSERT INTO transaction (customer_id,trade_type,type,trade_id,to_from_customer_id,price,quantity,status,pair_id,created_at,transanction_master_id) values ('" + dedd[i].customer_id + "','Buy','Limit','" + dedd[i].trade_id + "','" + mcustId + "','" + dedd[i].money + "','" + dedd[i].quantity + "','Fully Executed','" + dedd[i].pair_id + "','" + created_at + "','" + transactionmasterdata[0].id + "'),('" + mcustId + "','Sell','Market','" + dedd[i].trade_id + "','" + dedd[i].customer_id + "','" + dedd[i].money + "','" + dedd[i].quantity + "','Fully Executed','" + dedd[i].pair_id + "','" + created_at + "','" + transactionmasterdata[0].id + "');"

                                        connection.query(sql4, function(err, rows, fields) {
                                            if (!err) {


                                                inner_callback(null);
                                            } else {

                                                inner_callback(err);
                                            };
                                        });
                                    } else {

                                        inner_callback(err);
                                    }
                                })

                            }
                        })
                    } else {

                        inner_callback(err);

                    }
                })
            },
            function(err) {
                if (err) {
                    reject(err)

                    console.log(err)
                } else {
                    resolve("ok")

                }
            });
    })
}



function pardb(dedd, mcustId) {
    return new Promise(function(resolve, reject) {

        var i = dedd.length
        async.forEachOf(dedd, function(error, i, inner_callback) {
                let sql1 = "UPDATE buy SET status = 'Partially Executed',quantity='" + dedd[i].newquantity + "' WHERE id ='" + dedd[i].trade_id + "'";

                connection.query(sql1, function(err, rows, fields) {
                    if (!err) {

                        console.log("done")
                        //inner_callback(null);
                        let sql2 = "INSERT INTO transaction (customer_id,trade_type,type,trade_id,to_from_customer_id,price,quantity,status,pair_id,created_at) values ('" + dedd[i].customer_id + "','Buy','Limit'," + dedd[i].trade_id + "','" + mcustId + "','" + dedd[i].money + "','" + dedd[i].quantity + "','Partially Executed','" + dedd[i].pair_id + "','" + created_at + "'),('" + mcustId + "','Sell','Market'," + dedd[i].trade_id + "','" + dedd.customer_id + "','" + dedd[i].money + "','" + dedd[i].quantity + "','Partially Executed','" + dedd[i].pair_id + "','" + created_at + "');"



                        connection.query(sql2, function(err, rows, fields) {
                            if (!err) {

                                inner_callback(null);
                            } else {

                                inner_callback(err);
                            };
                        });
                    } else {

                        inner_callback(err);

                    }
                })
            },
            function(err) {
                if (err) {
                    reject(err)


                } else {
                    resolve("ok")


                }
            });
    })
}

如何将这三个函数合并为一个,如果发生错误,则回滚节点js中的所有函数。所有函数一个接一个地工作正常但我必须包含回滚所有函数以防出错。 仅针对单个用户的第一功能更改状态。 第二个函数与数组一起工作并更改当前数组中所有用户的状态。 第三个功能也与第二个功能相同,但具有不同的状态

1 个答案:

答案 0 :(得分:0)

我强烈建议您使用sequelize.js。这更容易理解。有一个名为transactions的部分,其中包含实现事务所需的所有信息(包括提交和回滚)。但是,在您深入研究此中间件之前,建议您阅读有关Promise chains的内容。通常,您在最后一个then提交事务,并在catch error部分回滚。 换句话说,当一切正常时,将提交事务,如果发生错误,则整个链将回滚到原来的状态。这是一个简单的示例:

sequelize.transaction().then(async transaction => {
    // firstPromise (you should pass transaction inside the query function)
  .then(()=>{
    // second promise
    // you can return a value from this promise to the next one
  })
  .then(()=>{
    // third  promise
  })
  .then(()=>{
    // final state
    transaction.commit();
  })
  .catch(err => {
      transaction.rollback();
  });
});