我打破了我的承诺 [英] I Broke My Promise

查看:105
本文介绍了我打破了我的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以..我正在学习如何承诺最难的时间。

So.. I'm having the hardest time learning how to Promise.

我正在使用 bluebird https://github.com/petkaantonov/bluebird )按照我的建议 - 为了驯服我的回调地狱我一直在得到。示例:

I'm using bluebird (https://github.com/petkaantonov/bluebird) as suggested to me -- in order to tame my callback hell I've been getting. Example:

function login(req,res,con,mysql,P) {
var ref = undefined;
    con.getConnection(function(err,connection) {
        if (err) console.log("Get Connection Error.. "+err);
        con.query('SELECT password,id FROM player WHERE name='+mysql.escape(req.body.user),function(err,rows,fields) {
            if (err) throw err;
            if (!rows[0]) {
                res.send({
                    "msg":"Your username and or password was incorrect.",
                    "flag":true,
                    "title":": Login Failed"
                });
            }
            if (rows[0].password !== "undefined") {
                if (hash.verify(req.body.pass,rows[0].password)) {
                    req.session.loggedIn = true;
                    req.session.user = rows[0].id;
                    ref = new P(rows[0].id,con,req);
                    res.send({
                        "msg":"You have logged in!",
                        "flag":false,
                        "title":": Logged In"
                    });
                } else {
                    res.send({
                        "msg":"Your username and or password was incorrect.",
                        "flag":true,
                        "title":": Login Failed"
                    });
                }
            }
        });
        connection.release();
    });
    console.log(ref);
    return ref;
}

这是令人讨厌的,它充满了回调,函数返回 ref 在查询回调完成执行之前。

It's nasty, it's full of callbacks, and the function returns ref before the query callback is finished executing.

解决方案:承诺!

我尝试使用快速启动转换我的函数..所以我 promisefyAll '我的 mysql 模块在创建之前连接:

I tried to convert my function using the quick start.. so I promisefyAll'd my mysql module before creating the connection:

var mysql = require("mysql");
var Promise = require("bluebird");
Promise.promisifyAll(mysql);

我写的函数如下:

function login(req,res,con,mysql,P) {
    var ref = undefined;
    Promise.promisify(con.getConnection)().then(function(connection) { //updated line returns error no method promisify. Bluebird v. 1.1.1
        con.query('SELECT password,id FROM player WHERE name='+mysql.escape(req.body.user)).then(function(rows,fields) {
            if (hash.verify(req.body.pass,rows[0].password)) {
                req.session.loggedIn = true;
                req.session.user = rows[0].id;
                ref = new P(rows[0].id,con,req);
                res.send({
                    "msg":"You have logged in!",
                    "flag":false,
                    "title":": Logged In"
                });
            } else {
                res.send({
                    "msg":"Your username and or password was incorrect.",
                    "flag":true,
                    "title":": Login Failed"
                });
            }
        });
        return ref;
    });
}

但我一直得到 TypeError:无法调用方法'那么'未定义在Object.login(/var/www/post/posts.js:36:22)

TypeError:undefined不是Pool的函数。< anonymous> (/var/www/node_modules/mysql/lib/Pool.js:53:14)

错误。有人可以帮我理解如何实现查询我的数据库(正确)的承诺吗?

Errors. Can somebody help me understand how to implement promises for querying my database (correctly)?

编辑(回复接受:):这是我如何调用登录功能:

Edit (post answer acceptance:): here is how I call the login function:

app.post("/login",function(req,res) {
    Player = post.login(req,res,con,mysql,p);
    console.log(Player); // logs [Object object]
}); //inside the login function, it logs the object like it should


推荐答案

当你宣传原型时,承诺返回方法将具有*异步后缀

When you promisify a prototype, the promise returning methods will have *Async suffix

宣传的想法是假装该库设计为返回承诺首先。您不应该在运行时期间在应用程序代码中调用promisify,而应该在您的appliation bootstrap init代码或类似代码中调用promisify。

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");
var Promise = require("bluebird");
//Only need to be called once per application so probably not here
Promise.promisifyAll(require("mysql/lib/Connection").prototype);
Promise.promisifyAll(require("mysql/lib/Pool").prototype);

function login(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 = new P(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:

function login(req,res,con,mysql,P) {
    return Promise.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 = new P(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) {

    }); 
})

这篇关于我打破了我的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆