promise面试题

250 阅读1分钟

题目1:

红灯3秒亮一次,绿灯1秒亮一次,黄灯2秒亮一次,使用promise让三个灯不断交替重复亮灯

解析:

    红灯3秒亮一次,绿灯1秒亮一次 ,黄灯2秒亮一次,意思就是3秒执行一次red函数,
    2秒执行一次green函数,1秒执行一次yellow函数,不断交替重复亮灯,意思就是按照这个顺
    序一直执行这3个函数,这可以利用递归来实现。 

代码如下:

    let red = () => console.log("红灯亮了")
    let green = () => console.log("绿灯亮了")
    let yellow = () => console.log("黄灯亮了")
    // 这里就依次打印出 红灯亮了 -- 绿灯亮了 -- 黄灯亮了  但只是一次执行
    // light(3000,red).then(res=>{
    //   return light(1000,green)  // 默认返回成功状态的promise 值为undefined
    // }).then(res=>{
    //   return light(2000,yellow)
    // })
    // 如何让他循环起来呢  写个死循环或者说是递归
    let runing = () => {
      light(3000, red).then(res => {
        return light(1000, green)  // 默认返回成功状态的promise 值为undefined
      }).then(res => {
        return light(2000, yellow)
      }).then(res => {
        runing()
      })
    }
    runing()

image.png

趣味版本

  <ul style="list-style: none;display:flex;width:120px;justify-content: space-around;">
    <li id="red" style="width:30px;height:30px;border-radius: 50%;background-color: #25232315;"></li>
    <li id="yellow" style="width:30px;height:30px;border-radius: 50%;background-color: #25232315;"></li>
    <li id="green" style="width:30px;height:30px;border-radius: 50%;background-color: #25232315;"></li>
  </ul>
    function setBgc(color){
      const $ = $=>document.querySelectorAll($)
      $(`#${color}`)[0].style.backgroundColor = color
      $('li').forEach((item)=>item.id !== color?item.style.backgroundColor = '#25232315':null)
    }

    let red = () => setBgc('red')
    let green = () => setBgc('green')
    let yellow = () => setBgc('yellow')
    
    
    
    let light = function (timer, colorFn) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          colorFn()
          resolve()
        }, timer)
      })
    }
    
    
    // 如何让他循环起来呢  写个死循环或者说是递归
    let runing = () => {
      light(3000, red).then(res => {
        return light(1000, green)  // 默认返回成功状态的promise 值为undefined
      }).then(res => {
        return light(2000, yellow)
      }).then(res => {
        runing()
      })
    }
    runing()
    

结果:

image.png

image.png

image.png