走进Promise-第五弹:将then方法的参数变为可选参数

912 阅读1分钟

前面几弹剖析了promise的内部基本实现原理,也对then方法的使用做了深入了解,我们知道then方法是有两个参数,这两个参数是回调函数,分别是成功的回调函数失败的回调函数,那么真实使用的情况是then方法中的参数,是可传可不传的,现在我们自己的testPromise中两个回调函数还是必传,所以接下来需要把这部分可选参数的逻辑加入代码中。

如下例子:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Promise 测试</title>
  </head>
  <body>
    <script>
      var promise = new Promise(function (resolve, reject) {
        resolve(100);
      })

      // then参数变为可选
      promise.then()
        .then()
        .then()
        .then(value => console.log(value)); // 100

    </script>
  </body>
</html>

**结果打印为100,**说明前面几次的调用then方法不传入参数,那么就将当前值传递给下一个then方法的回调函数。

解决思路:在then方法中加入对回调的判断回调函数是否存在,如果存在就使用,如果不存在就将当前的promise状态传递到下一个then的调用,直到传递给有回调函数的then方法。

**testPromise.js**中:

then (successCallback, failCallback) {
    successCallback = successCallback ? successCallback : value => value;
    failCallback = failCallback ? failCallback : reason => reason;
 
    // ...其余代码省略
}

**index.js**中:

// 6.then方法可选参数链式调用
promise
.then()
.then()
.then()
.then(value => console.log("可选参数执行结果>>>", value))

执行结果: