Promise相关题目

  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相关题目)