前端面试押题
  • HTML
    • 有哪些新标签?
    • SVG 的区别是什么?
    • 如何理解 HTML 中的语义化标签
  • CSS
    • 如何清除浮动?
    • CSS 选择器优先级如何确定?
    • BFC 是什么
    • 两种盒模型(box-sizing)的区别?
    • 如何实现垂直居中?
  • JavaScript 押题基础篇
    • new 做了什么?
    • JS 如何实现类?
    • JS 的闭包是什么?怎么用?
    • JS 如何实现继承?
    • JS 的立即执行函数是什么?
    • JS 的数据类型有哪些?
    • 原型链是什么?
    • 这段代码中的 this 是多少?
  • JavaScript 押题手写篇
    • 手写数组去重
    • 手写简化版 Promise
    • 手写 AJAX
    • 手写深拷贝
    • 手写节流 throttle、防抖 debounce
    • 手写发布订阅
    • 手写 Promise.all
  • DOM 押题
    • 请简述 DOM 事件模型
    • 手写可拖曳 div
    • 手写事件委托
  • HTTP 押题
    • 说说同源策略和跨域
    • POST 的区别有哪些?
    • TCP 三次握手和四次挥手是什么?
    • Session、Cookie、LocalStorage、SessionStorage 的区别
    • HTTP 缓存有哪些方案?
    • HTTPS 的区别有哪些?
    • HTTP/2 的区别有哪些?
  • React 押题
    • 什么是高阶组件 HOC?
    • React Hooks 如何模拟组件生命周期?
    • 你如何理解 Redux?
    • React 有哪些生命周期钩子函数?数据请求放在哪个钩子里?
    • React 如何实现组件间通信
    • 虚拟 DOM 的原理是什么?
    • Vue DOM diff 的区别?
    • DOM diff 算法是怎样的?
  • Node.js 押题
    • 浏览器里的微任务和任务是什么?
    • EventLoop 是什么?
    • koa.js 的区别是什么?
  • TypeScript 押题
    • JS 的区别是什么?有什么优势?
    • any、unknown、never 的区别是什么?
    • TS 工具类型 Partial、Required、Readonly、Exclude、Extract、Omit、ReturnType 的作用和实现?
    • interface 的区别是什么?
Powered by GitBook
On this page
  1. JavaScript 押题手写篇

手写简化版 Promise

记忆题,写博客吧

class Promise2 {
  #status = 'pending'
  constructor(fn){
    this.q = []
    const resolve = (data)=>{
      this.#status = 'fulfilled'
      const f1f2 = this.q.shift()
      if(!f1f2 || !f1f2[0]) return
      const x = f1f2[0].call(undefined, data)
      if(x instanceof Promise2) {
        x.then((data)=>{
          resolve(data)
        }, (reason)=>{
          reject(reason)
        })
      }else {
        resolve(x)
      }
    }
    const reject = (reason)=>{
      this.#status = 'rejected'
      const f1f2 = this.q.shift()
      if(!f1f2 || !f1f2[1]) return
      const x = f1f2[1].call(undefined, reason)
      if(x instanceof Promise2){
        x.then((data)=>{
          resolve(data)
        }, (reason)=>{
          reject(reason)
        })
      }else{
        resolve(x)
      }
    }
    fn.call(undefined, resolve, reject)
  }
  then(f1, f2){
    this.q.push([f1, f2])
  }
}

const p = new Promise2(function(resolve, reject){
  setTimeout(function(){
    reject('出错')
  },3000)
})

p.then( (data)=>{console.log(data)}, (r)=>{console.error(r)} )
Previous手写数组去重Next手写 AJAX

Last updated 3 years ago