Magician
Magician

Reputation: 2113

expired keys in nodeJs

I want to create some pattern for key-value store, with structure like:

function ItemObject(value1, value2, value3) {
    this.value1 = value1;
    this.value2 = value2;
    this.value3 = value3;
    // or whatever object needs.
}

then, I make a function like:

function keystore() {
    this.keys = new Array();
    this.decaytime = 50000; //in second
}

keystore.prototype.storeKey = function(key, itemObject) {
    this.keys[key] = itemObject;
    setTimeout(this.removeKey(key), this.decaytime);
}

keystore.prototype.removeKey = function(key) {
    console.log('removing ' + key);
    console.log(this.keys);
    if (this.keys[key]) {
        delete this.keys[key]
    }
    console.log('done');
    console.log(this.keys);
}


module.exports = keystore;

Now, I want to make that this.keys[keyid] removed after decaytime. How can I do that? Because this.removeKey() is outside setTimeout() scope, and obviously, not a function since it is not declared yet in setTimeout. I need removeKey() as part of object because I want to remove key prematurely if needed, so I would keep removeKey()

Thank you

EDIT: I found a way, but it is ugly.

keystore.prototype.storeKey = function(key, itemObject) {
    this.keys[key] = itemObject);
    var _this = this;
    setTimeout(function() {_this.removeKey(key);}, this.decaytime);
}

Is there any proper way?

Upvotes: 0

Views: 297

Answers (1)

Niraj Chauhan
Niraj Chauhan

Reputation: 7880

Use arrow functions for setTimeout, your this context will be maintained.

function keystore() {
    this.keys = new Array();
    this.decaytime = 2000; //in second
}

keystore.prototype.storeKey = function(key, itemObject) {
    this.keys.push(key, itemObject);
    setTimeout(() => this.removeKey(key), this.decaytime);
}

keystore.prototype.removeKey = function(key) {
    console.log('removing ' + key);
    console.log(this.keys);
    if (this.keys[key] != null) {
        this.keys = this.keys.filter((item, index) => index !== key);
    }
    console.log('done');
    console.log(this.keys);
}

Upvotes: 1

Related Questions