gpt4 book ai didi

node.js - 使用 bluebird 进行 Node -redis promise 化

转载 作者:太空宇宙 更新时间:2023-11-03 22:53:01 26 4
gpt4 key购买 nike

我尝试将 Promise 与 node-redis 包一起使用,但无法使用 on.connect() 方法。

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

bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);

// callback version
app.get('/redis', function(req, res) {
client.set("foo_rand000000000000", "some fantastic value", function(err, reply) {
if (err) {
console.log(err);
} else {
console.log(reply);
}
res.end();
});
});

// promisified version
app.get('/redis', function(req, res) {
return client.setAsync("foo_rand000000000000", "some fantastic value").then(function(return) {
console.log(return); // returns OK
client.quit();
});
});

但是我被下面的问题困住了,我该如何 promise 呢?

// example
client.on("connect", function () {
client.set("foo_rand000000000000", "some fantastic value", redis.print);
client.get("foo_rand000000000000", redis.print);
});

我尝试了下面的方法,但它不起作用,我在命令行上看不到响应:

app.get('/redis', function(req, res) {
return client.onAsync("connect").then(function(res) {
console.log(res);
res.end();
});
});

最佳答案

像 Freyday siad 一样,on 不是异步方法,而是一个事件发射器,所以我强烈建议你不要 promise 它,但是嘿,如果你坚持的话,你可以这样做:

let _connectResolve, _connectReject, onConnected = new Promise((resolve, reject) => {
_connectResolve = resolve;
_connectReject = reject;
}), redis = require("redis"),
client = redis.createClient();

client.on('connect', _connectResolve);

// usage example:
onConnected.then(() => {
client.setAsync("foo_rand000000000000", "some fantastic value").then(redis.print);
client.getAsync("foo_rand000000000000").then(redis.print);
});

如果您担心,您必须等待客户端连接才能获取/设置内容,您可以将所有调用链接到 onConnected promise 。例如:

app.get('/redis', (req, res) => {
onConnected
.then(() => client.setAsync("foo_rand000000000000", "some fantastic value"))
.then(() => res.end());
});

关于node.js - 使用 bluebird 进行 Node -redis promise 化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35422487/

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