Promise及async/await 等待某个值变为true后,才执行接下来的代码

场景:需要等待其他事件触发vuex中的方法,使得值haveGroupList改为true后,才能执行之后接下来的代码

Promise写法:

getData(){
    let r = new Promise((resolve) =>{
      let timer = setInterval(() =>{
          if(this.haveGroupList){
            clearInterval(timer)
            resolve(true)
          }
      },100)
    })
            
     r.then((res) =>{
        console.log('ddddddddddddddo somting')
            ...
    })
}
        

async/await 写法:

async getData(){
    await new Promise( (resolve) =>{
      let timer = setInterval(() =>{
          if(this.haveGroupList){
              clearInterval(timer)
              resolve(true)
          }
      },100)
    })
    
    console.log('ddddddddddddddo somting')
    ...  

}

 

posted @ 2020-03-03 20:47  Niky99  阅读(2575)  评论(0编辑  收藏  举报