promise specification and application (advanced)

##promise parsing

*What is asynchronous?

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

        //循环执行
        let count = 1
        let timer = setInterval(function () {
            count++
            console.log('in', count);
        }, 1000);
        console.log('out');
        setTimeout(function () {
            clearInterval(timer)
            console.log('clear');//第5秒后清空循环器
        }, 5000);
        //看不见的队列,存放着需要默默执行的命令

###1. Process & Thread

####a. Concept & Difference

####b. Interview questions

* Mapping to front-end-browser

Chrome opens a new window, is it a process or a thread (can be understood as mutual cooperation, independent of each other)? => process (can be understood as a complete independent system)

* diverge

Direction 1: Window (inter-process) communication?=>storage | cookie=>The difference between multiple storages=>Application scenario=>Combined resume project

Direction 2: Browser principle (interviews for intermediate and senior positions are mostly)

###2.EVENT-LOOP

####a. Execution stack

*js single-threaded language, single-step execution

        function func2() {
            throw new Error('please check your call stack');
        }
        function func1() {
            func2() 
        }
        function func() {
            func1()
        }
        func()

 ####b. Interview questions

        //    执行顺序
        setTimeout(() => {
            console.log('count');//5.宏任务2
        }, 0);

        new Promise(resolve => {
            console.log('new Promise');//1.属于同步进入主线程 宏任务1
            resolve()
        }).then(() => {
            console.log('Promise then');//3.微任务1
        }).then(() => {
            console.log('Promise then then');//4.微任务2
        })
        console.log('hi');//2.同步+宏任务1
        //任务拆分 : macro | micro
        //同步 | 异步

event-table: can be understood as asynchronous to be executed

event queue: asynchronous queue

Synchronously walk the synchronous execution stack, and asynchronously walk the asynchronous event queue.

###promiseization => chaining

#### a. Theory - Callback Hell

       request.onreadystatechange = () => {
            //回调后处理
        }
        //加时延
        setTimeout(() => {
            request.onreadystatechange = () => {
                //回调后处理
                setTimeout(() => {
                    //处理
                    request.onreadystatechange = () => {
                        //......
                    }
                });
            }
        });

        //promise化
        new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve('ok')
            });
        }).then(res => {
            request()
        }).catch(err => {
            console.log(err);
        })

 Multiple asynchronous sequential executions => compound chain calls

       function wait500(input) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve(input + 500)
                }, 500);
            })
        }

        function wait1000(input) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve(input + 1000)
                }, 1000);
            })
        }

        const p = new Promise((resolve, reject) => {
            resolve(1)
        })
        p.then(wait500)
            .then(wait1000)
            .then(wait500)
            .then(wait1000)
            .then(res => {
                console.log('end', res);
            })

        //全部执行完成回调
        Promise.all([wait500, wait1000]).then(res => {
            console.log('all end', res);
        })
        //有执行完成的立刻操作
        Promise.race()([wait500, wait1000]).then(res => {
            console.log('all end', res);
        })

####b. Interview-promise

*1. Promise status - pedding | fulfilled | rejected

Executor (executor): Execute immediately when new Promise is received, receive two parameters, resolve | rejected

*2. The default state of promise? How does the state flow? - The default is pedding, state flow: pedding=>fulfilled | pedding=>rejected

Internal maintenance success value:underfined | thenable | promise

Internal maintenance failure reason resaon

*3.promise return value? -then method: receive onFulfilled and onRejected

If then, the promise has succeeded, execute onFulfilled, parameter value

If then, the promise has failed, execute onRejected, parameter resaon

If there is an exception in then, execute onRejected

*Follow-up: Handwritten?

        const PENDING = 'PENDING'
        const FULFILLED = 'FULFILLED'
        const REJECTED = 'REJECTED'

        class Promise {
            constructor(executor) {
                //1.默认状态-PENDING
                this.status = 'PENDING'
                //2.内部维护的变量值
                this.value = undefined
                this.reason = undefined

                //成功的回调
                let resolve = value => {
                    //状态流转
                    this.status = FULFILLED
                    this.value = value
                }

                //失败的回调
                let reason = reason => {
                    //状态流转
                    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) {
                    onFulfilled(this.reason)
                }
            }
        }

        //异步怎么办?
        const PENDING = 'PENDING'
        const FULFILLED = 'FULFILLED'
        const REJECTED = 'REJECTED'

        class Promise {
            constructor(executor) {
                //1.默认状态-PENDING
                this.status = 'PENDING'
                //2.内部维护的变量值
                this.value = undefined
                this.reason = undefined

                //存放回调
                this.onResolvedCallbacks = []
                this.onRejectedCallbacks = []

                //成功的回调
                let resolve = value => {
                    //状态流转
                    this.status = FULFILLED
                    this.value = value
                    this.onResolvedCallbacks.forEach(fn => fn())
                }

                //失败的回调
                let reason = reason => {
                    //状态流转
                    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) {
                    onFulfilled(this.reason)
                }
                if (this.status === PENDING) {
                    //存放队列
                    this.onResolvedCallbacks.push(() => {
                        onFulfilled(this.value)
                    })
                    this.onRejectedCallbacks.push(() => {
                        onFulfilled(this.reason)
                    })
                }
            }
        }

Guess you like

Origin blog.csdn.net/huihui_999/article/details/131735913