理解Promise

90 阅读2分钟

什么是异步?

    // 异步执行
    let count = 1;
    let timer = setTimeout(() => {
        count++;
        console.log('in', count);
    }, 1000)
    console.log('out', count);
    
    // 循环执行 + 终止
    let count = 1;
    let timer = setInterval(() => {
        count++;
        console.log('in', count);
    }, 1000);
    console.log('out', count);

    setTimeout(() => {
        clearInterval(timer);
        console.log('in', count);
    }, 5000);
    // 看不见的队列,存放着他需要默默执行的命令

什么是进程和线程?

  1. 概念和区别 进程是CPU资源分配的最小单位,线程是CPU调度的最小单位

image.png

  1. 面试题: 问:映射到浏览器,chrome新开一个窗口,tab页是进程还是线程? - 进程,每个tab是独立运行的
 发散:
      方向一:窗口(进程间)通信? 浏览器的存储 - storage, cookie => 多种存储的区别
      方向二:浏览器原理(中高级)

image.png

EVENT_LOOP

  1. 执行栈 - JS单线程语言,单步执行
    function run() {
        fun1();
    }
    function fun1() {
        throw new Error('plz check ur call stack');
    }
    run();
  1. JS 堆栈的执行顺序与堆栈溢出 => 性能优化
    function func() {
        func();
    }
    func();

执行顺序题

    setTimeout(()=>{
      console.log('Time out'); // 异步 macro 
    });
    Promise.resolve(1).then(()=>{
      console.log('promise'); // 微任务 micro
    });
    console.log('hi'); // 同步 macro
    // h p t 

Promise

a. Promise出现是为了解决回调地狱(回调的无穷嵌套)
b. Promise 的异步顺序执行 => 链式调用
c. 面试题:
    描述Promise框架 - 规范
    1. Promise 有哪几种状态? 对应值有哪 - pending,fulfilled,rejected
    2. new Promise 执行器 executor(),执行器参数是? - resolve, reject
    3. Promise默认状态是? Promise状态流转? - 默认pending, p => f, p => r
    4. Promise value是保存成功状态的枚举? - undefined / thenable / Promise
    5. Promise 失败状态的值? - reason保存失败
    描述Promise接口
    6. Promise一定会有then, then接收来源?
       两个回调 onFulfilled(value) + onRejected(reason)
    // 三个状态:PENDING FULFILLED REJECTED
    const PENDING = 'PENDING'
    const FULFILLED = 'FULFILLED'
    const REJECTED = 'REJECTED'

    class Promise { // 类
        constructor(executor) { // 构造
            // 默认状态的处理: PENDING
            this.status = PENDING

            // 成功状态的值
            this.value = undefined
            // 失败状态的值
            this.reason = undefined

            // 成功状态的回调
            let resolve = value => {
                if (this.status === PENDING) {
                    this.status = FULFILLED
                    this.value = value
                }
            }

            // 失败状态的回调
            let reject = reason => {
                if (this.status === PENDING) {
                    this.status = REJECTED
                    this.reason = reason
                }
            }
            
            try {
                executor(resolve, reject)
            } catch (error) {
                reject(error)
            }
        }

        then(onFulfilled, onRejected) {
            if (this.status === FULFILLED) {
                onFulfilled(this.value)
            }

            if (this.status === REJECTED) {
                onRejected(this.reason)
            }
        }
    }
    
    const promise = new Promise((resolve, reject) => {
        resolve('成功')
    }).then(data => {})
    .catch(err => {})

    // 异步
    // 区别 - 依次调用
    class Promise { // 类
        constructor(executor) { // 构造
            // 默认状态的处理: PENDING
            this.status = PENDING

            // 成功状态的值
            this.value = undefined
            // 失败状态的值
            this.reason = undefined

            // 存放成功的回调
            this.onResolvedCallbacks = []
            // 存放失败的回调
            this.onRejectedCallbacks = []

            // 成功状态的回调
            let resolve = value => {
                if (this.status === PENDING) {
                    this.status = FULFILLED
                    this.value = value

                    // 依次调用对应函数的执行
                    (this.onResolvedCallbacks || []).forEach(fn => fn())
                }
            }

            // 失败状态的回调
            let reject = reason => {
                if (this.status === PENDING) {
                    this.status = REJECTED
                    this.reason = reason

                    // 依次调用对应函数的执行
                    (this.onRejectedCallbacks || []).forEach(fn => fn())
                }
            }

            try {
                executor(resolve, reject)
            } catch (error) {
                reject(error)
            }
        }

        then(onFulfilled, onRejected) {
            if (this.status === FULFILLED) {
                onFulfilled(this.value)
            }

            if (this.status === REJECTED) {
                onRejected(this.reason)
            }

            if (this.status === PENDING) {
                this.onResolvedCallbacks.push(() => {
                    onFulfilled(this.value)
                })
                this.onRejectedCallbacks.push(() => {
                    onRejected(this.reason)
                })
            }
        }
    }

    // 启示:同步 => 异步
    // 顺序和空间的关系