美文网首页
Promise相关题目

Promise相关题目

作者: 斯里兰卡的小狮子 | 来源:发表于2020-08-06 18:47 被阅读0次
    1. 实现一个person对象,有eat和dinner两种方法
      请用实例【依次类推】
      new Person('Tom').sleep(10).eat('dinner');
      //输出 console.log("hello Tom");
      //等待10s后输出
      console.log("sleep 10s");
      console.log("eat dinner");
    class Person{
        constructor(name){
            this.name = name
            console.log(`hello ${this.name}`)
            this.promise = Promise.resolve()
        }
        sleep(second){
            this.promise = this.promise.then(function(){
                return new Promise((resolve,reject)=>{
                  setTimeout(function(){
                    console.log(`sleep ${second}s`)
                    resolve()
                  },second*1000)  
                })
            })
            return this;
        }
        eat(food){
            this.promise.then(function(){            
                console.log(`eat ${food}`);
            })
            return this
        }
    }
    new Person('Tom').sleep(10).eat('dinner');
    
    1. 3s之后亮红灯一次,再过2s亮绿灯一次,再过1s亮黄灯一次,
      用promise实现多次交替亮灯的效果(可以用console.log模拟亮灯)
    function light(color, second) {
      return new Promise((resolve, reject) => {
        setTimeout(function () {
          console.log(color);
          resolve();
        }, second * 1000);
      });
    }
    
    // list:[{color:xx,second:xx}]
    function orderLights(list) {
      let promise = Promise.resolve();
      list.forEach((item) => {
        promise = promise.then(function(){
          return light(item.color, item.second);
        })    
      })
      promise.then(function(){
        return orderLights(list)
      })
    }
    orderLights([
      { color: "red", second: 3 },
      { color: "green", second: 2 },
      { color: "yellow", second: 1 }
    ]);
    
    1. 下面代码输出什么?
    const promise = Promise.resolve(1).
    then(2).
    then(Promise.resolve(3)).
    then(console.log)
    // 1
    

    相关文章

      网友评论

          本文标题:Promise相关题目

          本文链接:https://www.haomeiwen.com/subject/plvmrktx.html