我正在构建节点js中的REST API,我需要从外部api(bitgo api' s)中检索一些值,然后将这些数据插入到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');
});
});
}
});