gpt4 book ai didi

javascript - 如何使用 ioredis 在 nodejs 中链接返回?

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

我正在使用 ioredis我想返回下面示例中的路径和值,一直到匿名函数。

console.log(
function (jsonGraphArg) {
return Redis.hget(jsonGraphArg[0], jsonGraphArg[1], function(error, result){
result = JSON.parse(result);
return {
path: [jsonGraphArg[0], jsonGraphArg[1], jsonGraphArg[2][0]],
value: result[jsonGraphArg[2][0]]
};
});
}
);

我希望 console.log() 中的结果是这样的:

{
path: "something",
value: "something else"
}

但它却给了我:

{
_bitField: 1,
_fulfillmentHandler0: [Function: successAdapter],
_rejectionHandler0: [Function: errorAdapter],
_progressHandler0: undefined,
_promise0: [Function],
_receiver0: [Circular],
_settledValue: undefined
}

最佳答案

首先,您尝试记录函数声明而不是函数执行结果。

console.log(
(function (jsonGraphArg) {
return Redis.hget(jsonGraphArg[0], jsonGraphArg[1], function(error, result){
result = JSON.parse(result);
return {
path: [jsonGraphArg[0], jsonGraphArg[1], jsonGraphArg[2][0]],
value: result[jsonGraphArg[2][0]]
};
});
})();
);

此代码将为您提供函数执行的结果。

第二个问题是Redis.hget是一个异步函数。要在 redis 返回结果后立即获得结果,您需要使用回调。

var callback = function(res) {
console.log(res);
}

(function (jsonGraphArg, callback) {
return Redis.hget(jsonGraphArg[0], jsonGraphArg[1], function(error, result){
result = JSON.parse(result);
return callback({
path: [jsonGraphArg[0], jsonGraphArg[1], jsonGraphArg[2][0]],
value: result[jsonGraphArg[2][0]]
});
});
})();

使用这段代码,当 Redis 返回数据时,它将调用带有 res 参数的 callback 函数,该参数将是您的具有路径和值属性的对象。

关于javascript - 如何使用 ioredis 在 nodejs 中链接返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32230118/

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