美文网首页
手写promise

手写promise

作者: 曹锦花 | 来源:发表于2019-09-25 14:08 被阅读0次
function MyPromise(callback) {
  // 定义 promise 内部的 status 和 value 值
  let _this = this
  this.status = 'pending'
  this.value = null
  this.resolveFunArr = []
  this.rejectFunArr = []

  function resolve(value) {
    if (_this.status === 'pending') {
      _this.status = 'resolved'
      _this.value = value
      _this.resolveFunArr.forEach(item => {
        item(_this.value)
      });
    }
  }
  function reject(value) {
    if (_this.status === 'pending') {
      _this.status = 'rejected'
      _this.value = value
      _this.rejectFunArr.forEach(item => {
        item(_this.value)
      })
    }
  }
  // try {
  callback(resolve, reject)
  // } catch (err) {
  // reject(err)
  // }
}

MyPromise.prototype.then = function (resolve, reject) {
  let _this = this
  if (_this.status == 'resolved') {
    resolve(_this.value)
  }

  if (_this.status == 'resolved') {
    reject(_this.value)
  }
  if (_this.status == 'pending') {
    _this.resolveFunArr.push(resolve)
    _this.rejectFunArr.push(reject)
  }
}

var testPromise = new MyPromise((resolve, reject) => {
  setTimeout(() => {
    var number = Math.random();
    if (number <= 0.5) {
      resolve('less than 0.5');
    } else {
      reject('greater than 0.5');
    }
  }, 1000)
})

testPromise.then(data => {
  console.log(data)
}, dataReject => {
  console.log(dataReject)
})

相关文章

  • 手写Promise

    手写 Promise 我们会通过手写一个符合 Promise/A+ 规范的 Promise 来深入理解它,并且手写...

  • 手写 Promise 系列 --- 3

    在前两篇(手写 Promise 系列 --- 1)和(手写 Promise 系列 ---2) 中,达成了3个目标 ...

  • 手写Promise

    $ 正常的promise用法   $ 手写的Promise   # 测试可行性

  • 手写promise

    手写promise 带大家手写一个 promis。在手写之前我会先简单介绍一下为什么要使用promise、prom...

  • 纯手写实现自己的nodejs promise 库

    纯手写实现自己的nodejs promise 库什么是Promise?promise 链Async/Await后续...

  • 手写基础 promise

    1. 前言 玩下吧 手写 promise,看看能写成啥样 2. promise 基础结构 3. 手写`promi...

  • 手写 Promise

    一、Promise 是一个异步操作返回的对象,用来传递异步操作的消息。 Promise 介绍和使用详见: 认识并使...

  • 手写Promise

  • 手写Promise

    Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大。 这篇博客有关于P...

  • 手写promise

    本章节纯粹是对promise手写实现。如果不了解promise自行了解再来学习本章知识。promise初体验首先,...

网友评论

      本文标题:手写promise

      本文链接:https://www.haomeiwen.com/subject/ucsgyctx.html