I Broke My Promise
So.. I'm having the hardest time learning how to Promise. I'm using bluebird (https://github.com/petkaantonov/bluebird) as suggested to me -- in order to tame my callback hell I've
Solution 1:
When you promisify a prototype, the promise returning methods will have *Async suffix
The idea of promisification is to pretend as if the library was designed to return promises to begin with. You should not call promisify in application code during runtime, but in your appliation bootstrap init code or similar.
var mysql = require("mysql");
varPromise = require("bluebird");
//Only need to be called once per application so probably not herePromise.promisifyAll(require("mysql/lib/Connection").prototype);
Promise.promisifyAll(require("mysql/lib/Pool").prototype);
functionlogin(req,res,con,mysql,P) {
return con.getConnectionAsync().then(function(connection) {
return connection.queryAsync('SELECT password,id FROM player WHERE name='+
mysql.escape(req.body.user)).spread(function(rows, fields) {
if (hash.verify(req.body.pass,rows[0].password)) {
req.session.loggedIn = true;
req.session.user = rows[0].id;
var ref = newP(rows[0].id,con,req);
res.send({
"msg":"You have logged in!",
"flag":false,
"title":": Logged In"
});
return ref;
} else {
res.send({
"msg":"Your username and or password was incorrect.",
"flag":true,
"title":": Login Failed"
});
}
}).finally(function() {
connection.release();
});
});
}
A future version will have much better resource management and you will be able to do:
functionlogin(req,res,con,mysql,P) {
returnPromise.using(con.getConnectionAsync(), function(connection) {
return connection.queryAsync('SELECT password,id FROM player WHERE name='+
mysql.escape(req.body.user));
}).spread(function(rows, fields) {
if (hash.verify(req.body.pass,rows[0].password)) {
req.session.loggedIn = true;
req.session.user = rows[0].id;
var ref = newP(rows[0].id,con,req);
res.send({
"msg":"You have logged in!",
"flag":false,
"title":": Logged In"
});
return ref;
} else {
res.send({
"msg":"Your username and or password was incorrect.",
"flag":true,
"title":": Login Failed"
});
}
});
}
How to use the result:
app.post("/login",function(req,res) {
post.login(req,res,con,mysql,p).then(function(Player) {
});
})
Post a Comment for "I Broke My Promise"