简体   繁体   English

如何在当前的JavaScript代码段中“返回此”以满足调用者的链接而不会破坏我的ESLint规则?

[英]How can I 'return this' in the current JavaScript snippet to cater for chaining in the caller without breaking my ESLint rules?

I have the following code. 我有以下代码。 It works perfectly and the caller needs each part to return this due to chaining: 它完美地工作,并且调用者需要每个部分由于链接而return this

module.exports = function(res){
return {
    success: function(content, contentType, resultCode) {
        sendResponse(
            res,
            content,
            validateContentType(contentType),
            validateResultCode(resultCode||'ok')
        )
        return this
    },
    error: function(resultCode, content, contentType){
        sendResponse(
            res,
            content,
            validateContentType(contentType),
            validateResultCode(resultCode||'bad_request')
        )
        return this
    },
    end: function(callback){
        res.end()
        callback&&callback()
        return this
    }
}
}

The thing is that I need my code to pass a set of ESLint rules. 问题是我需要我的代码来传递一组ESLint规则。 The above fails with the following, where line 36 is the first line of code: 上面的代码失败,其中第36行是第一行代码:

36:18  warning  Unexpected unnamed function                                            func-names
36:26  error    Missing space before function parentheses                              space-before-function-paren
36:31  error    Missing space before opening brace                                     space-before-blocks
38:12  warning  Unexpected unnamed method 'success'                                    func-names
38:20  error    Missing space before function parentheses                              space-before-function-paren
43:34  error    Infix operators must be spaced                                         space-infix-ops
43:41  error    Missing trailing comma                                                 comma-dangle
44:5   error    Missing semicolon                                                      semi
45:15  error    Missing semicolon                                                      semi
47:10  warning  Unexpected unnamed method 'error'                                      func-names
47:18  error    Missing space before function parentheses                              space-before-function-paren
47:52  error    Missing space before opening brace                                     space-before-blocks
52:34  error    Infix operators must be spaced                                         space-infix-ops
52:50  error    Missing trailing comma                                                 comma-dangle
53:5   error    Missing semicolon                                                      semi
54:15  error    Missing semicolon                                                      semi
56:8   warning  Unexpected unnamed method 'end'                                        func-names
56:16  error    Missing space before function parentheses                              space-before-function-paren
56:26  error    Missing space before opening brace                                     space-before-blocks
57:13  error    Missing semicolon                                                      semi
58:4   error    Expected an assignment or function call and instead saw an expression  no-unused-expressions
58:12  error    Infix operators must be spaced                                         space-infix-ops
58:24  error    Missing semicolon                                                      semi
59:15  error    Missing semicolon                                                      semi
60:4   error    Missing trailing comma                                                 comma-dangle
61:3   error    Missing semicolon                                                      semi
62:2   error    Missing semicolon                                                      semi

The following snippet passes the rules but does NOT return this since that would give another ESLint error due to the no-invalid-this rule and critically, no longer works, breaking the chaining: 下面的代码段传递了规则,但是没有return this因为由于no-invalid-this规则会产生另一个ESLint错误,并且严重地,不再有效,打破了链接:

module.exports = res => ({
success: (content, contentType, resultCode) => {
    sendResponse(
        res,
        content,
        validateContentType(contentType),
        validateResultCode(resultCode || 'ok'),
    );
},
error: (resultCode, content, contentType) => {
    sendResponse(
        res,
        content,
        validateContentType(contentType),
        validateResultCode(resultCode || 'bad_request'),
    );
},
end: (callback) => {
    res.end();
    if (callback) {
        callback();
        return undefined;
    }
    return undefined;
},
});

My question is how do I adapt the second snippet (or indeed the first) to be functionally identical to the first but still pass the ESLint rules? 我的问题是我如何调整第二个片段(或者第一个片段)在功能上与第一个片段相同但仍然通过ESLint规则? How can I return correctly to allow chaining with the caller? 如何正确返回以允许与呼叫者链接?

My .eslintrc.json : 我的.eslintrc.json

{
  "extends": "airbnb-base",
 "rules": {
// use tabs, not spaces, and in switch statements the case statement should indent again (the default is to be level with the switch)
    "indent": [ "error", "tab", { "SwitchCase": 1 } ],
// if you want to put a blank line at the beginning or end of a block, knock yourself out
"padded-blocks": [ "off" ],
// i like tabs. besides, we set indent to require them
"no-tabs": [ "off" ],
// seriously, who cares if there's a blank line at the end of the file or not?
"eol-last": [ "off" ],
// sometimes having a long single line makes sense, this also seems buggy and inconsistent, so we ignore it
"max-len": [ "off" ],
// webstorm repeatedly tries to add it for us. it's easier not to fight it, even if it's not required.
"strict": [ "off" ],
// when setting the property of an object, you can specify the name even if it's unnecessary (ie: { foo: foo })
"object-shorthand": [ "off" ],
// unused vars are an error, except for function arguments.
// particularly with callbacks we may not use all the args, but we still like knowing they're available
"no-unused-vars": [ "error", { "vars": "all", "args": "none", "ignoreRestSiblings": true } ],
// you don't have to use operator assignment if you don't want to
"operator-assignment": [ "warn" ],
// we don't want else to be on the same line as the closing } of an if statement
"brace-style": [ "error", "stroustrup" ],
// warn about overly complex code that you may want to refactor
"complexity": [ "warn", 15 ],
// it's possible that implicit coercion is not what you intended. webstorm warns about it, so should we
"no-implicit-coercion": [ "warn" ],
// if you're using 'this' somewhere that isn't a class you're probably doing something wrong
"no-invalid-this": [ "error" ],
// if you're not modifying the variable used in a loop condition, you've probably done something wrong...
"no-unmodified-loop-condition": [ "warn" ],
// don't use .call or .apply when you don't need to
"no-useless-call": [ "warn" ],
// we want to slap you if you don't update your jsdoc, but not necessarily break one of your fingers
"valid-jsdoc": [ "warn" ],
// forgetting to return after calling a callback is an easy mistake to make, so we'll warn you if you are
"callback-return": [ "warn" ]
  }
}

Well as the docs of the eslint rules mentions , you need to give your anonymous function expressions a name (so they won't be anonymous anymore). 正如eslint规则的文档所提到的那样 ,你需要给你的匿名函数表达式一个名字(所以它们不再是匿名的)。
By the way this is good practice because you can debug it better and call it as a recursive function if you need. 顺便说一下,这是一个很好的做法,因为你可以更好地调试它,并在需要时将其称为递归函数。

Then why not just give them names? 那为什么不给他们起名字呢?

module.exports = function exports(res) {
  return {
    success: function success(content, contentType, resultCode) {
      sendResponse(
        res,
        content,
        validateContentType(contentType),
        validateResultCode(resultCode || 'ok'),
      );
      return this;
    },
    error: function error(resultCode, content, contentType) {
      sendResponse(
        res,
        content,
        validateContentType(contentType),
        validateResultCode(resultCode || 'bad_request'),
      );
      return this;
    },
    end: function end(callback) {
      res.end();
      if (callback) {
        callback();
        return undefined;
      }
      return this;
    },
  }
}

I settled for a third snippet that is functionally equivalent to the first and has no ESLint errors but only ESLint warnings: 我选择了第三个片段,它在功能上与第一个片段相同,没有ESLint错误,只有ESLint警告:

module.exports = function (res) {
return {
    success: function (content, contentType, resultCode) {
        sendResponse(
            res,
            content,
            validateContentType(contentType),
            validateResultCode(resultCode || 'ok'),
        );
        return this;
    },
    error: function (resultCode, content, contentType) {
        sendResponse(
            res,
            content,
            validateContentType(contentType),
            validateResultCode(resultCode || 'bad_request'),
        );
        return this;
    },
    end: function (callback) {
        res.end();
        if (callback) {
            callback();
            return undefined;
        }
        return this;
    },
};

}; };

  36:18  warning  Unexpected unnamed function          func-names
  38:12  warning  Unexpected unnamed method 'success'  func-names
  47:10  warning  Unexpected unnamed method 'error'    func-names
  56:8   warning  Unexpected unnamed method 'end'      func-names

However, if someone would care to adapt snippet 2 in my question to work as though it 'returned this', passing my ESLint errors, warnings and being functionally equivalent to snippet 1 or my answer then I will mark that answer as correct! 但是,如果有人愿意在我的问题中调整片段2来工作,好像它“返回了这个”,传递我的ESLint错误,警告并在功能上等同于片段1或我的答案,那么我会将答案标记为正确!

I'll guess you are supposed to use method syntax for your methods, instead function expressions: 我猜你应该为你的方法使用方法语法,而不是函数表达式:

module.exports = (res) => ({
    success(content, contentType, resultCode) {
        sendResponse(
            res,
            content,
            validateContentType(contentType),
            validateResultCode(resultCode || 'ok'),
        );
        return this;
    },
    error(resultCode, content, contentType) {
        sendResponse(
            res,
            content,
            validateContentType(contentType),
            validateResultCode(resultCode || 'bad_request'),
        );
        return this;
    },
    end(callback) {
        res.end();
        if (callback) {
            callback();
        }
        return this;
    },
});

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

相关问题 我可以将我的 React.Component 子类添加到 ESLint 规则吗? - Can I add my React.Component subclass to ESLint rules? 如何使用 PHP 在我的页面上填充我的 HTML 表而不破坏我的 JavaScript? - How would I populate my HTML table on my page using PHP without breaking my JavaScript? 如何将我的 Firebase CDN 片段链接到我的 JavaScript 文件? - How can I link up my Firebase CDN snippet to my JavaScript file? JavaScript:如何在不中断功能的情况下将false返回链接? - JavaScript: how to return false to link without breaking function? NodeJS:如何在不使用require的情况下包含一些javascript代码段? - NodeJS: How can I include some javascript code snippet without using require? 如何将回调函数中的值返回给调用者? - How can i return a value from a callback function to the caller? 如何解决一致返回错误是 eslint? - How can I resolve a consistent-return error is eslint? 如何简化创建 SVG 图像的 JavaScript 代码而不破坏它? - How can I simplify this JavaScript code that creates SVG images without breaking it? 如何在不破坏javascript确认的情况下在我的消息资源中添加撇号? - how to put an apostrophe in my message resource without breaking the javascript confirm? Javascript返回值,不中断循环 - Javascript Return Value without breaking loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM