【问题标题】:Redis async library does not have function that are in redis library for node.jsRedis 异步库没有用于 node.js 的 redis 库中的功能
【发布时间】:2020-09-11 18:37:14
【问题描述】:

我需要使用 redis 异步函数。目前我正在使用redis库。我的要求是在这个库中我使用exists 函数来检查一个键是否在redis 中。如果不是,我将在此存在函数中进行数据库调用并尝试返回数据库响应。这是代码的一部分:-

var redis = require('redis');
var client = redis.createClient(port, 'anyhost');
client.exists(obj.empId, function(err, reply) {

  if (reply == 0) {
    console.log('indb call');
    return db.one('SELECT * FROM iuidtest WHERE empid = $1', [obj.empId])
      .then(iuidtest => {
        console.log(iuidtest.iuid);
        return iuidtest.empid;

      })
  }
});

在这里,我可以在控制台中打印 iuid 值,但不能从中返回值。我在某处读到的原因可能是我从同步方法 client.exists 中的异步方法 db.one 返回值。 所以我尝试使用 redis-async 库。

var asyncredis = require('async-redis');
var myCache= asyncredis.createClient(port, 'vsseacgmy13');

但是这里这个 myCache 变量没有客户端变量中的像 exists() 这样的 redis 函数。我的要求是在检查缓存中的键后返回数据库调用值。有没有办法像使用另一个库或使这个存在函数异步这样我可以返回 DB 调用的值?

【问题讨论】:

  • 你能做到return await db.one()吗?如果是,问题就解决了。如果没有,你需要使用 Promise
  • No 当使用 db.one 的 await 时我不能这样做,因为错误消息是 await 只能在异步函数中使用。所以我认为存在函数必须是同步的。
  • 我也在 db,one 中使用 promise 来获取结果并将其记录到控制台。如果它在某个异步函数中,我什至可以从该函数返回。您能否解释一下如何使用承诺来解决我的问题,因为我无法理解。任何帮助是极大的赞赏。 :)
  • await can only be used inside an async function 当然可以,所以只需在函数名称前添加asyncclient.exists(obj.empId, async function(err, reply) {
  • 是的,这样我就可以将 await 添加到 db.one 函数中。但不幸的是,我仍然无法从这个 db.one 函数返回值。我认为问题可能是我的 redis 存在函数是同步的,所以我无法从其中的异步函数(db.one)返回值。还是我错了?

标签: javascript node.js asynchronous redis async-await


【解决方案1】:

两个异步函数完成后,只需将最终值传递给一个新函数并对其进行一些处理。

var redis = require('redis');
var client = redis.createClient(port, 'anyhost');

client.exists(obj.empId, function(err, reply) {
  if (reply == 0) {
    console.log('indb call');
    db.one('SELECT * FROM iuidtest WHERE empid = $1', [obj.empId])
      .then(iuidtest => {
        console.log(iuidtest.iuid);
        doSomethingWith(iuidtest.empid);
      })
  }
});

const doSomethingWith = empid => {
  console.log( "empid = ", empid );
}

【讨论】:

  • 谢谢。另一件事我仍然无法从 doSomethingWith 函数返回 empid 值。从现在开始,我在同步函数中得到了这个值,我该如何返回它?
  • 这样做是在函数中传递值并在函数中记录值。与仅在异步函数中记录值不是一回事吗?好像我在 doSomethingWith func 声明中添加了 return 语句,它不会返回值,因为无论如何都会在 async func 中调用这个 return 语句。我也不能将任何 this 值设置为 doSomethingWith 函数中的任何全局变量,然后在这些异步函数随后执行时返回它。
  • 为什么要“返回”这个值?回到哪里?使用它,它被定义在一个函数中,用它来做你的事情
  • 因为这个 db 调用我在一个 graphql 解析器函数中执行,该函数期望返回一个字符串值。所以基本上这个值是从那个解析器函数中返回的。我应该分享更多的代码来澄清吗?
  • 啊,这越来越复杂了。你不能把graphql解析器放在doSomethingWith()里面吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-01
  • 2013-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-01
  • 1970-01-01
相关资源
最近更新 更多