为什么这个异步功能没有等待

时间:2020-02-18 09:11:08

标签: javascript async-await

我具有以下功能

const refresh = async req => {
    const authorization = req.headers['authorization'];

    if (!authorization) throw new Error("You need to login");
    accesstoken = authorization.split(' ')[1];
    //..... a lot of code
}
module.exports =  {
    refresh
}

然后我在另一个文件中称呼它

    function requireLogin(req,res,next){
    try {

        const userId = isAuth(req)
        if (userId !== null) {
            next();
        }
    } catch (err) {
        if(err.message == "jwt expired"){
            console.log("jwt was expired")
            async function result(){
                console.log("inside result function")
                var data = await refresh(req)
                console.log(data) //undefined
            }
            result();
        }
        res.send({
            error: `${err.message}`
        })
    }
}

因此,它基本上不等待我的功能。 如果我在函数中使用console.log()期望的结果,则可以看到它正常发生,但是由于它没有等待,所以我无法将其记录在主文件中。

我不知道语法对我来说很好。

编辑:这是刷新的全部代码

const refresh = async req => {
const authorization = req.headers['authorization'];

if (!authorization) throw new Error("You need to login");
accesstoken = authorization.split(' ')[1];
var userId = verify(accesstoken, process.env.ACCESS_TOKEN_SECRET, { ignoreExpiration: true })
userId = userId.userId

var token = ""

db.query("SELECT * FROM user_permisson WHERE user_id='" + userId + "'").then(function (data) {
    var permited = [];
    console.log("permisos de usuario")
    delete data[0].user_id
    for (var key in data[0]) {
        if (data[0].hasOwnProperty(key)) {
            if (data[0][key] === true) {
                permited.push(key)
            }
            console.log(key + " -> " + data[0][key]);
        }
    }
    console.log(permited)

    //CASE 1(Front end): this is for the case when its coming from rect and is unable to read the private cookie, so it received an encrypted id that will identify the user so we are able to get its refresh token, client to server connection
    //now the we need to grab the refreshtoken of the user knowing its id
    db.query("SELECT * FROM users WHERE id='" + userId + "'").then(function (data) {
        var user = data;
        token = user[0].refreshtoken;
        var id = user[0].id;
        if (!token) return { accesstoken: '' };
        let payload = null;

        try {
            payload = verify(token, process.env.REFRESH_TOKEN_SECRET);
        } catch (err) {
            return { accesstoken: '' };
        }

        user = "";
        db.query("SELECT * FROM users WHERE id='" + id + "'").then(function (data) {
            user = data;
            if (!user) return { accesstoken: '' };
            //if user exists check if refreshtoken exist on user

            if (user[0].refreshtoken !== token) {
                return { accesstoken: '' }
            }

            //if token exist create a new Refresh and Accestoken
            const accesstoken = createAccessToken(user[0].id, permited);
            const refreshtoken = createRefreshToken(user[0].id);


            db.query("UPDATE users SET refreshtoken = '" + refreshtoken + "' WHERE id = '" + user[0].id + "';").then(function (data) {
                // sendRefreshToken(res, refreshtoken); //unnecesary
                console.log(accesstoken)
                return { accesstoken }; //THIS IS THE RETURN I WANT TO HAPPEN <---------------------------------------

            }).catch(function (error) {
                console.log("ERROR: ", error)
            })


        }).catch(function (error) {
            console.log("ERROR: ", error)
            return error;
        })
    })

}) }

0 个答案:

没有答案
相关问题