Promise相關(guān)題目

  1. 實(shí)現(xiàn)一個person對象,有eat和dinner兩種方法
    請用實(shí)例【依次類推】
    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實(shí)現(xiàn)多次交替亮燈的效果(可以用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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容