手写promise

javascript 技术 前端

JavaScript

2020-06-23 09:40:11

274

作者:黑夜男神

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Promise</title>
</head>

<body>
  <script>
    function Promise(fn) {
      var state = 'pending',
        value = null,

        callbacks = [];
      this.then = function (onFulfilled) {
        if (state === 'pending') {
          callbacks.push(onFulfilled);
          return this;

        }

        onFulfilled(value);
        return this;
      };


      function resolve(newValue) {
        value = newValue;
        state = 'fulfilled';
        setTimeout(function () {
          callbacks.forEach(function (callback) {
            callback(value);
          });
        }, 0);
      }
      fn(resolve);
    }


    new Promise(resolve => {
      setTimeout(() => {
        resolve(1)
      },1000)
    }).then((res) => {
      debugger
    })
  </script>

</body>

</html>

评论 (0)

用户名
邮箱
评论

    Copyright © 2020 darkNightMan All Rights Reserved Pro 黔ICP备20005477号