gpt4 book ai didi

node.js - 如何等到 Node 中的 redis 收到响应?

转载 作者:可可西里 更新时间:2023-11-01 11:09:09 24 4
gpt4 key购买 nike

我是 node 和 redis 的新手。我在我的 node 应用程序中使用 redis。我想检索以同步方式从 Redis 获取数据。这是我尝试过的。

var redis = require("redis"),
client = redis.createClient();

client.set('key',10,redis.print);

function getfn1(key){
client.get(key,function(err,reply){
if(err){
console.log('Response from getfn1:-');
console.log(err);
return;
}
console.log('Response from getfn1:-');
console.log(reply);
});
}

async function getfn2(key){
let response = await client.get(key);
console.log('Response from getfn2:-');
console.log(response);
}
console.log('1');
getfn1('key');
console.log('2');
getfn2('key');
console.log('3');

结果如下:

1
2
3
Response from getfn2:-
false
Response from getfn1:-
10

如您所见,我正在尝试在 getfn2() 中使用 async 和 await 等待 redis 的结果,但我得到的响应是“false”,而不是原始响应 10。如果您建议等待redis数据的方法。

最佳答案

async/await 语法旨在与 Promises 一起使用,但 redis 模块默认不返回 Promises。

如果你想使用 Promises,这就是 documentation说要做:

You can also use node_redis with promises by promisifying node_redis with bluebird as in:

var redis = require('redis');
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);

It'll add a Async to all node_redis functions (e.g. return client.getAsync().then())

// We expect a value 'foo': 'bar' to be present
// So instead of writing client.get('foo', cb); you have to write:
return client.getAsync('foo').then(function(res) {
console.log(res); // => 'bar'
});

您的 getfn2 函数将变为:

async function getfn2(key){
let response = await client.getAsync(key);
console.log('Response from getfn2:-');
console.log(response);
}

关于node.js - 如何等到 Node 中的 redis 收到响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51094249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com