# 链式优化

原文地址：<http://taobaofed.org/blog/2017/03/16/javascript-functional-programing/>

以前有听说过回调地狱，知道一层又一层的嵌套回调函数是很麻烦的事，会遇到一些作用域的问题，具体现在也说不明白了。记得是在《做质控报告》批量操作的功能。有很多报告，每一份报告又分章节，每一章节里的内容都是可以刷新替换的。比如表格和图片。在这里用到过回调函数的3级嵌套，功能还是实现了，就是代码的不好看，逻辑还可以更清晰得。

现在用Promise多重回调时，不用嵌套了，直接接着后面写。如同回调函数的链式优化一样。当我们要在一个函数里拿到某个值去应用到另一个函数时，我们来回调。

* 多重嵌套的例子 ，用于加减法的函数
* ```javascript
  function sum(a , b){
      return a+b ;
  }

  function sub(a,b){
      return a- b;
  }
  ```
* 当计算6+7+8+10-5+3-4+5:
* ```javascript
  sum(sub(sum(sub(sum(sum(sum(6,7),8),10),5),3),4),5)
  ```

这样太不方便查看，对后续的修改也麻烦。

使用链式优化，lodash也是这样的原理。

```javascript
const unit={
    chain(a){
        this._tem = a;
        return this;
    },
    sum(b){
     this._tem +=b ;
     return this ;
    },
    sub(c){
        this._tem +=c;
        return this;
    },
    value(){
        return this._temp;
    }
}

unit.chain(6).sum(7).sum(8).sum(10).sub(5).sum(3).sub(4).sum(5);
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sekin.gitbook.io/myjs/chapter1/lian-shi-you-hua.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
