【问题标题】:Fetching synchroneously from redis in Node through async/await通过 async/await 从 Node 中的 redis 同步获取
【发布时间】:2020-03-06 00:48:29
【问题描述】:

我从几天前开始学习 Java 中的 Javascript 和 Vue,但无法通过 async/await 解决我的 Node、Express 应用程序的问题。下面的代码从请求中接收股票符号列表,然后通过循环检查任何符号的详细信息是否已缓存在 redis 中。

var controllers = {
   getCurrentPrice: function(req, res) {
        var symbolsArray = req.body.symbols;
        var results = [];
        var tmpArray = [];

        _(symbolsArray).each( async function(symbol, iPos) {
            client.hget("realtime", symbol, function(err, reply)    {
                if(reply)   {
                    await results.push(reply);
                } else  {
                    await tmpArray.push(symbol);
                }
                console.log("reply", reply);
            });
        });
        console.log("Results so far ", results);
        if( !tmpArray || tmpArray.length == 0 ) { //will be fetching these now }
    }
}

在内部控制台语句中获取输出,但在外部控制台语句中没有。我尝试通过网络查看一些解决方案,例如通过 redis-co 来承诺 redis 调用,但无法完全解决它。

【问题讨论】:

  • 可能是你的promise失败了,你试过加.catch吗?

标签: javascript express redis


【解决方案1】:

这里有几个问题:

  1. .push() 的结果执行await 没有任何用处。你在承诺上使用await
  2. 您的 .each() 循环不会等待每个异步操作完成,因此您无法知道所有异步操作何时完成

我建议使用常规的for 循环,其中async/await 将暂停循环:

const util = require('util');
client.hgetP = util.promisify(client.hget);

var controllers = {
   getCurrentPrice: async function(req, res) {
        var symbolsArray = req.body.symbols;
        var results = [];
        var tmpArray = [];

        for (let symbol of symbolsArray) {
            let reply = await client.hgetP("realtime", symbol);
            if (reply) {
                results.push(reply);
            } else {
                tempArray.push(symbol);
            }
        }

        // do any further processing of tempArray here

        console.log(results);
        return results;    // this will be the resolved value of the returned promise
    }
}

示例用法:

obj.getCurrentPrice.then(results => {
     console(results);
}).catch(err => {
     console.log(err);
});

【讨论】:

  • 感谢您的帮助。 Redis 调用中的另一个问题我可以通过这里提到的 co-redis 解决 - stackoverflow.com/questions/35536710/…
  • @RajMalhotra - 如果这回答了您的问题,您可以通过单击答案左侧的复选标记向社区表明这一点。遵循正确的程序也会为您赢得一些声誉积分。
猜你喜欢
  • 1970-01-01
  • 2017-05-07
  • 1970-01-01
  • 1970-01-01
  • 2017-11-14
  • 2018-01-23
  • 2012-05-02
  • 1970-01-01
  • 2018-09-14
相关资源
最近更新 更多