gpt4 book ai didi

javascript - 使用 Node.js util 模块 promise 所有方法

转载 作者:行者123 更新时间:2023-12-04 12:03:32 26 4
gpt4 key购买 nike

我有一个 redis util,它看起来像:

const redis = require('redis')
const { promisify } = require('util')
const client = redis.createClient({
host: '127.0.0.1',
port: '6379'
})

module.exports = {
get: promisify(client.get).bind(client),
hget: promisify(client.hget).bind(client),
set: promisify(client.set).bind(client),
mset: promisify(client.mset).bind(client),
hset: promisify(client.hset).bind(client),
hmset: promisify(client.hmset).bind(client),
...
}

我想在不重复的情况下重写它。如何使用 promisify 导出客户端功能?迭代每种方法?

最初,我查看了 Object.keys(client)Object.getOwnPropertyNames(client)作为获取要映射的方法名称的起点,但这些数组都不包含它们。

编辑:这更接近,有没有更好的表达方式?
const promisifiedClient = {}

for (const fn in Object.getPrototypeOf(client)) {
if (typeof client[fn] === 'function') {
promisifiedClient[fn] = promisify(client[fn]).bind(client)
}
}

module.exports = promisifiedClient

Edit2:也许这行得通(如果不是没有一些我可能不需要/想要 promise 的 promise 功能的奇怪副作用?)
const redisFunctionList = Object.keys(Object.getPrototypeOf(client))

const promisifiedRedis = redisFunctionList.reduce((acc, functionName) => {
acc[functionName] = promisify(client[functionName]).bind(client)
return acc
}, {})

module.exports = promisifiedRedis

最佳答案

您可以使用 bluebird包,然后可以简单地 promise redis客户端。

const redis = require("redis");
const bluebird = require("bluebird");
const client = new redis.RedisClient();

/// promise based client of redis
/// storing it in a variable helps with intellisense
const promiseClient = bluebird.promisifyAll(client);

const main = async () => {
/// After that, we just call the default methods with an Async in the end
/// For Example:
/// client.get becomes client.getAsync
/// client.set becaomes client.setAsync
const data = await promiseClient.getAsync("foo");
console.log(data);
const message = await promiseClient.quitAsync();
console.log(message);
};

main();

module.exports = promiseClient;

关于javascript - 使用 Node.js util 模块 promise 所有方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53686376/

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