i have an async function which return 1 or 0 value on a js file, this it the code
checkAuthentication: async function (client) {
//search redis
//get value key "token"
try{
var tempValue, tempErr
client.get("token", async (err, value) => {
tempValue = value
tempErr = err
if (tempErr) { // kalo gk ada di redis
console.log(tempErr)
return 0
}
if (tempValue !== null) {//ADA DI REDIS
var start = new Date()
var responseRedis = JSON.parse(tempValue)
// console.log('this is old data' + responseRedis.accessToken)
var end = (new Date() - start)
console.info('Execution time: %d ms', end)
jwt.verify(responseRedis.accessToken, accessTokenSecret, function (err, decoded) {//check if token expired or not
if (err) {//TOKEN EXPIRED
console.log(err)
return 0
} else {//TOKEN TIDAK EXPIRED
//tuker token jd refreshesh token
const newRefreshToken = jwt.sign({ username: decoded.user_name }, accessTokenSecret, { expiresIn: '24h' });
var data_send_redis = JSON.stringify({
"accessToken": newRefreshToken,
});
//store to redis
// console.log('this is new data' + data_send_redis)
client.setex("token", 600, data_send_redis);
return 1
}
});
} else { //GK ADA DI REDIS TOKENYA
//LOG OUT
console.log('token not found')
return 0
}
})
}catch (err){
console.log(err)
return 0
}
}
in the other hand i trying to get the value in a variable named a in other js files
var a = await model_auth_token.checkAuthentication(client)
console.log('hasil check auth : return ' + a)
if(a == 0){
client.del('token', function(err, response) {
if (response == 1) {
console.log("Deleted Successfully!")
} else{
console.log("Fail to Delete")
console.log(err)
}
});
res.redirect('/panel/panel_login')
return
}
whenever i do console log result always shows undefined, i already add await or then on the function, but the console log result always shows undefined
You are returning from a.then or.catch callback, which is a function.
You need to wrap the client.get block in a Promise:
return new Promise((resolve, reject) => { ... });
Then, use resolve()
to 'succeed', and reject()
to 'fail'.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.