Асинхронный вызов, ожидание обещания - PullRequest
0 голосов
/ 10 января 2019

Я новичок в Node.js, в аутентификации, когда я запускаю код Promise всегда в ожидании.

Error

is Authenticated ?:  Promise { pending }

Обещание {в ожидании}

Я пробовал другой метод, чтобы использовать ожидание, но я не мог найти правильный путь. Спасибо за помощь.

Код

return new Promise((resolve, reject) =>
{
console.log(email, password);
var isAuthenticated = false;
isAuthenticated= model.authenticate(email, password).then(function(result){
    //console.log(model.authenticate(email, password));
    console.log("is Authenticated ?: ",isAuthenticated);
    if(isAuthenticated) {
        console.log(isAuthenticated);
        console.log("Success!");
        res.render('/home');
    } else {
        console.log("ko");
        res.redirect("/");
    }
    }).catch(function(error) {
        console.log(error);
    });
});




User.prototype.authenticate = function( email, password ) {
    connection = this.connection;
    return new Promise(function(resolve, reject){
        connection.query('SELECT * FROM users WHERE email = ? AND Password = ? AND is_deleted = 0',[email, password], 
        function (error, results, fields) {
            if (error){
                console.log("error ocurred",error);
                reject(error);
                return false;
            } else {
                resolve(results);
                return true;
            }
        });
    });
};

1 Ответ

0 голосов
/ 10 января 2019

Позволяет реорганизовать первый блог, назвав его обещаниеФункции . Оно может быть написано таким образом, чтобы оно всегда возвращало обещание.

 const promiseFunction = function (req, res, next) {
// I am assuming it is a express middleware and res is passed as the function arguments.
return new Promise((resolve, reject) => {
    console.log(email, password);
    var isAuthenticated = false;
    isAuthenticated = model.authenticate(email, password)
        .then(function (result) {
            //console.log(model.authenticate(email, password));
            console.log("is Authenticated ?: ", isAuthenticated);
            if (isAuthenticated) {
                console.log(isAuthenticated);
                console.log("Success!");
                res.render('/home');
                return resolve()
            }
            else {
                console.log("ko");
                res.redirect("/");
                return resolve()
            }
        }).catch(function (error) {
            console.log(error);
            return reject(error)
        });
});
}

Приведенный выше код всегда возвращает обещание. Лучший подход будет

const promiseFunction = function (req, res, next) {
// I am assuming it is a express middleware and res is passed as the function arguments.
return model.authenticate(email, password)
    .then(function ({ isAuthenticated }) {
        //console.log(model.authenticate(email, password));
        console.log("is Authenticated ?: ", isAuthenticated);
        if (isAuthenticated) {
            console.log(isAuthenticated);
            console.log("Success!");
            res.render('/home');
        }
        else {
            console.log("ko");
            res.redirect("/");
        }
    })
}

и функция аутентификации будет:

User.prototype.authenticate = function (email, password) {
connection = this.connection;

return new Promise(function (resolve, reject) {
    connection.query('SELECT * FROM users WHERE email = ? AND Password = ? AND is_deleted = 0', [email, password], function (error, results, fields) {
        if (error) {
            console.log("error ocurred", error);
            return reject(error);
        }
        else {
            var newResponse = Object.assign({}, response, {isAuthenticated: true})
            return resolve(newResponse);
        }
    });
});
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...