gpt4 book ai didi

javascript - 在redis中存储node.js setTimeout的返回值

转载 作者:IT老高 更新时间:2023-10-28 23:08:43 24 4
gpt4 key购买 nike

我在 Node.js 中使用 setTimeout,它的行为似乎与客户端 setTimeout 不同,因为它返回的是对象而不是数字。我想把这个存储在redis中,但是由于redis只存储字符串,所以我需要将对象转换为字符串。但是,使用 JSON.stringify 会引发循环引用错误。如果我希望能够从 redis 中获取该对象并在其上调用 clearTimeout,如何将其存储在 redis 中?

最佳答案

您不能将对象存储在 Redis 中。 setTimeout 方法返回一个 Handler(对象引用)。​​

一个想法是在内存中创建自己的关联数组,并将索引存储在 Redis 中。例如:

var nextTimerIndex = 0;
var timerMap = {};

var timer = setTimeout(function(timerIndex) {
console.log('Ding!');

// Free timer reference!
delete timerMap[timerIndex];
}, 5 * 1000, nextTimerIndex);

// Store index in Redis...

// Then, store the timer object for later reference
timerMap[nextTimerIndex++] = timer;

// ...
// To clear the timeout
clearTimeout(timerMap[myTimerIndex]);

关于javascript - 在redis中存储node.js setTimeout的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11300654/

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