Interview questions for 1299 yuan sold at the front end of the MOOC [Phase 1] JS-day02


Previous MOOC CSS interview questions, link addressNext
MOOC JS interview questions, link address

1. js interview questions

1. event loop event loop mechanism

Please add a picture description
insert image description here

the case
insert image description here

  • console.log ('Hi') is first executed in 2.Call Stack, cleared after execution, and then go to 1.Browser console. Output Hi
    insert image description here
  • setTimeout ( function cb1() ); Execute in 2.Call Stack first, enter 3.Web APIs, stay here for 5s.
  • And clear the setTimeout cb1 in 2.Call Stack . This is where the execution ends.
  • Go down and execute console.log('Bye')

- console.log('Bye') is first executed in 2.Call Stack, cleared after execution, and then go to 1.Browser console. Output Bye

insert image description here

  • After Bye is output, all executable codes are executed, and 2. Call Stack is cleared. At this time, Timer cb1 is still in 3.5s in Web APIs has not yet arrived.
  • At this time, the Event loop mechanism is started, the synchronization code is executed, and 2. Call Stack is empty.

Explanation: No code can be pushed into the Call Stack for the time being, and the Event loop mechanism will be started immediately, which is the event loop mechanism started by the browser kernel. At this time, the Event loop will search from the (asynchronous callback) Callback Queue over and over again. If there is any function, it will take it over. Take it and push it into the Call Stack for execution.

  • Wait until 3, Timer cb1 timer in Web Apis ends, push into 4.Callback Queue, and clear Timer cb1 of Web Apis.
  • At this time, the Event loop finds that there is an executable function in the callback queue Queue, and pushes it into the 2.Call Stack, and the Queue clears the cb1 function.
  • The existing cb1 function in the Call Stack executes the log.('cb1') inside and pushes it into 1.Browser console, and the console prints cb1. And clear the log('cb1') in the Call Stack
  • Call Stack will look for executable logs from the cb1 function. At this time, there is no executable content in the cb1 function, and the cb1 function method will be cleared.

So far, the entire code has been executed

The browser console outputs
Hi Bye cb1

insert image description here

insert image description here


2. Promise interview questions

1. What are the three states of promise? status and changes

insert image description here

insert image description here

the case
insert image description here
insert image description here


2.then and cath change state

insert image description here

3. Please answer the following promise interview questions

insert image description here

insert image description here
insert image description here
insert image description here


3. Handwritten promise to load pictures

insert image description here

insert image description here
insert image description here


4. The relationship between async/await and promise?

insert image description here
insert image description here

  • the case

insert image description here
insert image description here
insert image description here

insert image description here

  • Look at the following question.
    insert image description here
    On await on const c, if you want to catch errors, you can use try catch to catch them.

insert image description here


5. Asynchronous nature, see the following async/await order question?

insert image description here

  • Answer
    insert image description here
    insert image description here

insert image description here
insert image description here

insert image description here

3. Explain the macro task macroTask and micro task microTask?

insert image description here
insert image description here
insert image description here

insert image description here

  • the case
    insert image description here
    insert image description here
    insert image description here
    insert image description here

4. Handwritten Promise function, with a lot of content

insert image description here

./MyPromise.js file

class MyPromise {
    
    
  // 状态 [等待 实现了 拒绝了]
  state = 'pending' // 状态, 'pending' 'fulfilled' 'rejected'
  value = undefined // 成功后的值
  reason = undefined // 失败后的原因

  // 如果 resolve成功状态.then(fn1,fn2) 其中一个会被立即执行
  // 此时如果 p1.then(fn1,fn2) = pending状态.then(fn1,fn2) 
  // 这时就无法判断 fn1 和fn2那个先执行,就需要将如下俩函数,存储起来
  resolveCallbacks = [] // pending 状态下,储存成功的回调
  rejectCallbacks = [] // pending 状态下,储存失败的回调

  // 构造函数
  constructor(fn) {
    
    
    // 成功
    const resolveHandler = (value) => {
    
    
      if (this.state === 'pending') {
    
    
        this.state = 'fulfilled' // 修改 成功状态
        this.value = value // 修改成功后的值
        // 这里是用this.value ,value不会在闭包中,减少内存
        // 执行函数 resolveCallback
        this.resolveCallbacks.forEach(fn => fn(this.value))
      }
    }
    // 失败
    const rejectHandler = (reason) => {
    
    
      if (this.state === 'pending') {
    
    
        this.state = 'rejected' // 修改 失败状态
        this, reason = reason // 修改失败后的值
        this.rejectCallbacks.forEach(fn => fn(this.reason))
      }
    }
    //  try 中执行函数 ,catch中抛出错误,提升稳定性
    try {
    
    
      fn(resolveHandler, rejectHandler)
    } catch (err) {
    
    
      rejectHandler(err)
    }
  }

  // .then 会有成功回调,和失败回调
  // 当 pending 状态下,fn1 fn2 会被存储到 callbacks 中
  // callbacks 中就是 resolveCallback 或 rejectCallbacks
  then(fn1, fn2) {
    
    
    // 成功
    // 判断fn1 是否是一个函数,如果是返回它自己,如果不是给它一个函数,返回它自己
    fn1 = typeof fn1 === 'function' ? fn1 : (v) => v
    // 失败
    fn2 = typeof fn2 === 'function' ? fn2 : (e) => e

    // 判断状态
    // 等待时
    if (this.state === 'pending') {
    
    
      // 当前状态是pending,无法判断,只能先存储起来
      const p1 = new MyPromise((resolve, reject) => {
    
    
        this.resolveCallbacks.push(() => {
    
    
          try {
    
    
            const newValue = fn1(this.value)
            resolve(newValue) // p1.value 变成了新的promise 对象
          } catch (err) {
    
    
            reject(err)
          }
        })
        this.rejectCallbacks.push(() => {
    
    
          try {
    
    
            const newReason = fn2(this.reason)
            reject(newReason) // p1.reason 变成了新的promise 对象
          } catch (err) {
    
    
            reject(err)
          }
        })
      })
      return p1
    }
    // 成功
    if (this.state === 'fulfilled') {
    
    
      const p1 = new MyPromise((resolve, reject) => {
    
    
        try {
    
    
          const newValue = fn1(this.value)
          resolve(newValue)
        } catch (err) {
    
    
          reject(err)
        }
      })
      return p1
    }
    // 失败
    if (this.state === 'rejected') {
    
    
      const p1 = new MyPromise((resolve, reject) => {
    
    
        try {
    
    
          const newReason = fn2(this.reason)
          reject(newReason) // 其实它是 赋值给 p1.reason
        } catch (err) {
    
    
          reject(err)
        }
      })
      return p1
    }
  }
  //  .catch 只有 失败回调。就是 then 的一个语法糖,简单模式。
  catch(fn) {
    
    
    return this.then(null, fn)
  }
}

Results of the
insert image description here


1. How will promise.all execute?
  • all represents all. Here the promises need to be executed successfully, and then return a new promise, including all the output results.
<body>
  <h1>MyPromise.all 会怎样执行</h1>
  <script src="./MyPromise.js"></script>
  <script>
    const p1 = new MyPromise((resolve, reject) => {
    
    
      // resolve(100) // 成功
      // reject('错误信息...') // 失败
      // 宏任务,异步回调
      setTimeout(() => {
    
    
        resolve(100)
      }, 500)
    })
    const p2 = MyPromise.resolve(200)
    const p3 = MyPromise.resolve(300)
    const p4 = MyPromise.reject('错误信息...')
    // 传入 promise 数组,等待所有的都 fulfilled 之后,
    // 返回新 promise , 包含所有的结果 
    const p5 = MyPromise.all([p1, p2, p3])
    p5.then(result => console.log('all result', result))
  </script>
</body>

In the ./MyPromise.js file

MyPromise.all = function (promiseList = []) {
    
    

  const p1 = new MyPromise((resolve, reject) => {
    
    
    const result = [] // 存储 promiseList 所有的结果
    const length = promiseList.length // 记录 promise数组长度
    let resolvedCount = 0 // 用于计数

    // forEach 中不可使用 index,因为index是同步的,forEach会立即执行完
    promiseList.forEach(p => {
    
    
      // promise 有可能是同步有可能是异步,有可能等待一两秒才执行
      p.then(data => {
    
    
        result.push(data)

        // resolvedCount 必须在 then里面做++ 
        // 坚决不能使用 index
        resolvedCount++
        if (resolvedCount === length) {
    
    
          // 已经 遍历到了最后一个 promise
          resolve(result)
        }
      }).catch(err => {
    
    
        reject(err)
      })
    })
  })
  return p1
}

Results of the
insert image description here


2. How will promise.race be executed?

  • race is the meaning of running a race. If you see that promise runs fast, execute that one first, and discard the latter
    insert image description hereinsert image description hereinsert image description here

DOM events and event loop

insert image description here

Guess you like

Origin blog.csdn.net/weixin_46426412/article/details/130473937