mysql——实现承诺和sql的最佳可行方法

ubof19bj  于 2021-06-20  发布在  Mysql
关注(0)|答案(0)|浏览(276)

我正在节点js中构建restapi,其中我需要从外部api(bitgoapi)检索一些值,然后将这些数据插入mysql数据库。为了实现这一点,我使用promises异步调用api,并在成功调用后将数据插入mysql catch 阻止在最后一个之后 then . 下面是我的代码片段。在错误处理或批量请求处理方面,这段代码还有改进的余地吗?我的目标是生产使用此代码。

app.post('/registeruser',function(req,res){

var userid = 2;
var username = req.body.username;
var firstname = req.body.firstname;
var lastname = req.body.lastname;
var email = req.body.email;
var password = req.body.password;
var bitcoincashreceivingaddress; 
var bitcoinreceivingaddress ;
var litecoinreceivingaddress ;
var user_balance = 0;

bitcoincashaddress()
.then(function(response,resolve){
    bitcoincashreceivingaddress = response;
    return bitcoinaddress();
}).then(function(body2){

    bitcoinreceivingaddress = body2;
    return litecoinaddress();

}).then(function(body3){
    litecoinreceivingaddress = body3;

    connection.query("Insert into Usertable(userid,Username,firstname,lastname,emailaddress,password) values ('"+userid+"','"+username+"','"+firstname+"','"+lastname+"','"+email+"','"+password+"')", function (error, results, fields) {
    if (error) throw error;
    console.log('The result is: ', results);
            });

    connection.query("Insert into Wallettable(receivingaddress,user_balance,user_id,coinid) values ('"+bitcoinreceivingaddress+"',"+user_balance+",'"+userid+"','1')", function (error, results, fields) {
    if (error) throw error;
    console.log('The result is: ', results);
            });
connection.end();

}).catch(function(err){
console.log(err);

});

function bitcoincashaddress (){
return new Promise (function (success, failure) { 
bitgo.coin('tbch').wallets().getWallet({ id: 'dumyaddress' })
.then(function(wallet) {
  return wallet.createAddress();
})
.then(function(newAddress) {
   var userbchaddress = newAddress.address;
   success(userbchaddress);

}).catch(function (err) {

       failure('Error in signup . Contact Admin');
    });
});

}

function bitcoinaddress (){
return new Promise (function (success, failure) { 
bitgo.coin('tbtc').wallets().getWallet({ id: 'dumyaddress' })
.then(function(wallet) {
  return wallet.createAddress();
})
.then(function(newAddress) {
   var userbtcaddress = newAddress.address;
   success(userbtcaddress);

}).catch(function (err) {

       failure('Error in creating bitcoincash address');
    });
});

}

function litecoinaddress (){
return new Promise (function (success, failure) { 
bitgo.coin('tltc').wallets().getWallet({ id: 'dumyaddress' })
.then(function(wallet) {
  return wallet.createAddress();
})
.then(function(newAddress) {
   var userltcaddress = newAddress.address;
   success(userltcaddress);

}).catch(function (err) {

       failure('Error in creating litecoin address');
    });
});

}
});

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题