async 異步執行的實現

const A = _ => new Promise((res, rej) => { // 設置A函數返回promise對象
       	 	setTimeout(function() {
	            console.log('1')
	            res('2')
	        }, 1000);
})
const B = async function() {
		      await A().then((res) => { // await會等待A()執行完,並且所有的then代碼也執行完,然後在向下執行,如果then代碼裏面的異步操作(如setTimeout,new Promise)不會執行。
		        console.log(res)
		        setTimeout(function(){  
		            console.log('4') // then中的代碼執行完直接進入下一個then,這個then 其實return了undifined            
		        }, 2000)
		        new Promise((res, rej) => { 
		       	 	setTimeout(function() {
			            console.log('5')
			            res('6')
			        }, 3000);
			    })
		      }).then(res => {
		          console.log(res)   // undifined
		      })
		      console.log('3')
}
console.log(B()) // Promise {<pending>}, 輸入結果爲1,2,undifined,4,5  

案例如:

getUserInfos() {   	
    	var prom =new Promise((resolve, reject) => {
	      this.$axiosGet({
	        url: "/userinfo",
	        success: _ => {       	
	          if (_.status == 1) {     
	            this.setUser(_.member);         	           
	          } else {
	            window.localStorage.removeItem("token");
	          }
	          resolve("ok")
	        },
	        error: _ => {
				 reject("failt")
			},
	      });
      })
    	return prom
}
async login(){
    await this.getUserInfos().then((res)=>{
		this.$router.push({ path: "/index" });              
	    },(rej)=>{
			this.$message({
	        message: "登錄失敗,請重試",
	        type: "error"
	    });
	})
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章