简体   繁体   English

JavaScript链接函数,最后一个方法返回“ undefined”

[英]JavaScript chaining functions, last methods returns 'undefined'

My app receives a base64 encoded value that is also encrypted. 我的应用程序接收到的base64编码值也已加密。 The data can come in a few different ways so I wanted to create chain-able methods to keep the code clean and modular. 数据可以以几种不同的方式出现,所以我想创建可链接的方法来保持代码的干净和模块化。

I want to be able write: decryptionChain.decodeBase64(b64Value).stringToBuffer().finallyDecrypt(); 我希望能够写出:decryptionChain.decodeBase64(b64Value).stringToBuffer()。finallyDecrypt();

When I run the code, the last property method "finallyDecrypt" returns as undefined. 当我运行代码时,最后一个属性方法“ finallyDecrypt”将返回未定义状态。

Why is the "finallyDecrypt" method coming back as undefined? 为什么“ finallyDecrypt”方法返回未定义状态? The rest all works and if I run ecryptionChain.decodeBase64(b64Value).stringToBuffer() I get back the Buffer I expect. 其余所有工作正常,如果我运行ecryptionChain.decodeBase64(b64Value).stringToBuffer(),我将得到期望的缓冲区。 It is only when the finallyDecrypt is chained in that I error out. 只有当finallyDecrypt被链接时,我才出错。

Here is the code: 这是代码:

   function decrypt(encrypted) {
    var decipher = crypto.createDecipheriv(algorithm, password, iv);
    decipher.setAuthTag(encrypted.tag);
    var dec = decipher.update(encrypted.content, 'hex', 'utf8');
    dec += decipher.final('utf8');
    return dec;
}

var decryptionChain = {

    currentValue:"",

    decodeBase64: function (encryptedValue){
        this.currentValue = new Buffer(encryptedValue.toString(), "base64");
        return this;
    },

    stringToBuffer: function() {
        if (this.currentValue) {
            myBuffer = JSON.parse(this.currentValue, function (key, value) {
                 return value && value.type === 'Buffer'
                    ? new Buffer(value.data)
                    : value;

            });

        }
        return myBuffer;
    },

    finallyDecrypt : function(myBuffer){
        if(myBuffer){
        decrypt(myBuffer);
        }
        return this;

    }
};

From the code shown, I have spotted some issues.First: 从显示的代码中,我发现了一些问题。

decryptionChain != decryptChain If its just a typo in the question, then disregard, if its not, please reffer to that. decryptionChain decryptChain != decryptionChain decryptChain如果只是问题的错字,请忽略,如果不是,请参考。

Please, use the var to decrease possibilities of scope errors, or "scoped variables" being left behind. 请使用var来减少范围错误或遗留“作用域变量”的可能性。

Second, dont use a string as a Boolean . 其次,不要将字符串用作Boolean

Third, you seem to have an issue with the return value && value.type === 'Buffer' ? new Buffer(value.data) : value; 第三,您似乎对return value && value.type === 'Buffer' ? new Buffer(value.data) : value; return value && value.type === 'Buffer' ? new Buffer(value.data) : value; , please assign before returning (not necessary, but simpler) ,请在返回之前分配(不必要,但更简单)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM