let arr = [1,2,3];

arr .reduce((promise,current)=>{

  return promise.then(()=>{

    return new Promise(resolve=>{

      setTimeout(()=>{

        console.log(current);

        resolve()

      },1000)

    })

  })

},Promise.resolve())

//总结:想要依次加载,上一个promise必须为完成状态,那么.then()里面的内容才可以继续执行,.then()之后的队列想要继续执行,那么当前.then()同样需要返回一个成功状态的promise

 

队列渲染示例:

let data = [
  {
    id:1,
    name:'jay',
    email:'jayking1314@126.com'
  },
  {
    id:2,
    name:'see',
    email:'jayking1314@126.com'
  }
]

function getUser(name){
  return new Promise((resolve,reject)=>{
    let theData = null;
    for(v of data){
      if(v.name === name){
        theData = v;
        break;
      }
    }
    if(theData){
      resolve(theData);
    }
    else{
      reject('no data...')
    }
  })
}


class User{
  constructor(name) {
    this.name = name;
  }
  render(users){
    users.reduce((promise,current)=>{
      return promise.then(()=>{
        return getUser(current).then(res=>{
          return this.view(res);
        })
      })
    },Promise.resolve())
  }
  view(user){
    return new Promise(resolve=>{
      setTimeout(()=>{
        let h2 = document.createElement('h2');
        h2.innerHTML = user.name;
        document.body.appendChild(h2);
        resolve();
      },1000)
    })
  }
}

new User().render(['jay','see']);

posted on 2021-06-21 16:40  皮杰克  阅读(226)  评论(0编辑  收藏  举报