public async validateToken(req, res): Promise<any> {
const token = req.headers.authorization.split(" ")[1] || req.params.token;
await this.redisClient.SISMEMBER("tokenBlackListSet", token, function(
err,
data
) {
if (data) { // here i get data=1 as token is present in tokenBlackListSet
return { // so this should be returned as json
status: 400,
error: "Invalid Token"
};
}
});
}
// in other async function
const response = await validateToken(req,res);
console.log(response) // returned value is always undefined
最佳答案
由于 SISMEMBER
方法返回一个 bool 值,而不是回调返回的值,您可以返回一个您在回调中解析的新 Promise :
public async validateToken(req, res): Promise<any> {
const token = req.headers.authorization.split(" ")[1] || req.params.token;
return new Promise(function (resolve, reject) { // Here I create a new Promise that will resolve (or reject) when your callback is called
this.redisClient.SISMEMBER("tokenBlackListSet", token, function(
err,
data
) {
if (err) { // If there is an error, we reject the promise
reject(err);
}
else if (data) { // If you have some data, the promise will resolve with the object
resolve({
status: 400,
error: "Invalid Token"
});
}
});
}
}
请注意,我删除了 await
,因为我们已经返回了一个 promise,所以它现在是多余的。
关于javascript - 异步函数不返回 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59389634/