【求助】我的promise写的又丑又蠢
在使用的promise的时候,我有希望在then之后再执行一个promise,但是多次执行之后就有很深的嵌套了,如下文的register,感觉没有抓住Promise的精髓,请大大们指导
//dboperation
exports.getPool = function(sql){
return new Promise(function(resolve,reject){
pool.getConnection(function(err,connection){
if(err){
reject('error connecting: ' + err.stack);
}else{
connection.query(sql,function(Err,Rows){
if(Err){
reject('error connecting: ' + Err.stack);
}
connection.release();
resolve(Rows)
});
}
})
});
}
//server
function register(socket,username, password, petname){
var REGISTER = 0,
p1 = dbobj.getPool("select * from user_table where Username='"+username+"'");
p1.then(function(data){
console.log(data);
if(data.length === 1){
REGISTER = -1;
socket.emit('REGIST_RESULT', { REGISTER: REGISTER});
}else{
var p2 = dbobj.getPool("select count(*) from user_table");
p2.then(function(data){
var id = data[0]["count(*)"] + 1,
sql = "insert into user_table (id,username,password,petname,avatar) values(?,?,?,?,?)",
inserts = [
id,
username,
password,
petname,
null
];
sql = mysql.format(sql,inserts);
var p3 = dbobj.getPool(sql);
p3.then(function(data){
var p4 = dbobj.getPool("select * from user_table where Username='"+username+"'");
p4.then(function(data){
console.log(data);
if(data.length === 1){
REGISTER = 1;
socket.emit('REGIST_RESULT', { REGISTER: REGISTER});
}else{
REGISTER = "error";
socket.emit('REGIST_RESULT', { REGISTER: REGISTER});
}
})
.catch(function(err){
console.log("insert into user_table"+err)
socket.emit('REGIST_RESULT', { REGISTER: REGISTER});
})
})
.catch(function(err){
console.log("insert into user_table"+err)
socket.emit('REGIST_RESULT', { REGISTER: REGISTER});
})
})
.catch(function(err){
console.log("select count(*) from user_table"+err)
socket.emit('REGIST_RESULT', { REGISTER: REGISTER});
});
}
})
.catch(function(err){
console.log("select * from user_table"+err)
socket.emit('REGIST_RESULT', { REGISTER: REGISTER});
});
}
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('REGISTER', function (username, password, petname) {
console.log(new Date());
register(socket,username, password, petname);
})
});
//client
socket.emit('REGISTER',"test", "zxcz", "petname");
socket.on('news', function (data) {
console.log(data);
})
socket.on("REGIST_RESULT",function(data){
console.log(data);
})