本文介绍了在redis中存储node.js setTimeout的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using setTimeout in Node.js and it seems to behave differently from client-side setTimeout in that it returns an object instead of a number. I want to store this in redis, but since redis only stores strings, I need to convert the object to a string. However, using JSON.stringify throws a circular reference error. How can I store this object in redis if I want to be able to fetch it from redis and call clearTimeout on it?

推荐答案

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

You cannot store the object in Redis. The setTimeout method returns a Handler (object reference).

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

One idea would be to create your own associative array in memory, and store the index in Redis. For example:

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]);

这篇关于在redis中存储node.js setTimeout的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 09:19