简体   繁体   English

Node.js返回值未定义

[英]Node.js return value is undefined

token in the below snippet is always undefined . 以下代码段中的token始终undefined Can someone help me out figuring what's wrong here? 有人可以帮我弄清楚这里出什么问题吗?

[err, token] = await to(comparePassHash(body.password, user.password));`

comparePassHash = async (pass, hash) => {
    bcrypt.compare(pass, hash, (err, token) => {
        if (err) TE(err);
        console.log('test');
        return token;
    });
};


to = (promise) => {
    return promise
    .then(data => {
        return [null, data];
    }).catch(err =>
        [pe(err)]
    );
};

It's undefined because that's what comparePassHash resolves. 它是undefined因为这是comparePassHash解决的。

async keyword won't work as you expect in that case. 在这种情况下, async关键字将无法正常运行。 You're returning token inside .compare function, not inside comparePassHash . 您将在.compare函数内而不是comparePassHash内部返回token You have to wrap bcrypt.compare with a Promise . 您必须用Promise包装bcrypt.compare

const comparePassHash = (pass, hash) => {
    return new Promise((resolve, reject) => {
        bcrypt.compare(pass, hash, (err, token) => {
            if (err) 
                return reject(err);
            console.log('test');
            return resolve(token);
        });
    });
};

Take your function: 发挥作用:

comparePassHash = async (pass, hash) => {
    bcrypt.compare(pass, hash, (err, token) => {
        if (err) TE(err);
        console.log('test');
        return token;
    });

   // implicit return: undefined
};

Without an await it will execute bcrypt.compare , it will not wait until it finishes, since it's not a promise, and it will exit the function, returning undefined since you're missing a return statement. 如果没有await ,它将执行bcrypt.compare ,直到它完成后才会等待,因为这不是一个承诺,并且它将退出该函数,由于缺少return语句而返回undefined

Another way is to use Util.promisify 另一种方法是使用Util.promisify

const { promisify } = require('util');
const comparePassHash= promisify(bcrypt.compare);

// This must be inside an async function
[err, token] = await to(comparePassHash(body.password, user.password));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM