javascript - 异步函数不返回 json 对象

标签 javascript node.js redis

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/

相关文章:

javascript - 从另一个对象数组中删除对象数组

php - 在 Laravel 中用于本地和生产的单个 Redis 配置?

javascript - 在 Kendo 数据网格中保留额外的 dataSource.read 参数

javascript - 使用 AJAX 的数据表中的子行

node.js - 无法更新 Node.js strip 订阅上的用法

javascript - 我怎样才能将一个配置对象共享给多个数据

node.js - OAuth 2.0 - 何时应使用刷新 token 更新访问 token ?

ruby-on-rails - Resque 和 Redis 服务器不能很好地相互配合

redis - 如何在redis中创建自己的数据库?

javascript - 如何关闭实现多选