promise寫法ajax
function runAsync1(){ var p = new Promise(function(resolve, reject){ //作一些異步操做 setTimeout(function(){ console.log('異步任務1執行完成'); resolve('隨便什麼數據1'); }, 1000); }); return p; } function runAsync2(){ var p = new Promise(function(resolve, reject){ //作一些異步操做 setTimeout(function(){ console.log('異步任務2執行完成'); resolve('隨便什麼數據2'); }, 2000); }); return p; } function runAsync3(){ var p = new Promise(function(resolve, reject){ //作一些異步操做 setTimeout(function(){ console.log('異步任務3執行完成'); resolve('隨便什麼數據3'); }, 2000); }); return p; } runAsync1() .then(function(data){ console.log(data); return runAsync2(); }) .then(function(data){ console.log(data); return runAsync3(); }) .then(function(data){ console.log(data); });
1. 包裝多個promise對象 api
2. 多個異步操做 要在回調裏 return下一個promise對象 ,操做多了,回調也是有點麻煩 promise
==============異步
async 寫法async
用同步的方式 寫異步操做this
獲取部門數據時,必須是return 異步對象url
若是return res = this.$ajax... 這樣會有問題 取值 undefinedcode
getDeptData(){ //獲取部門數據 return this.$ajax({ url: this.$ajax.apiUrl("/sys/dept/list"), method: "get", params: this.$ajax.adornParams() }); }, getRolesData(){ //獲取角色數據 return this.$ajax({ url: this.$ajax.apiUrl("/sys/role/all"), method: "get", params: this.$ajax.adornParams() }); }, async init(id){ try{ let res_dept = await this.getDeptData(); let res_role = await this.getRolesData(); this.deptList = this.$tool.treeDataTranslate(res_dept.data); this.roleList = res_role.data; this.dataForm.id = id; this.isEdit=false, this.visible = true; this.$nextTick(() => { this.$refs["dataForm"].resetFields(); }); if (!id) {// 新增 this.dataForm.deptName = null; console.log('新增', this.dataForm) } else {// 修改 this.isEdit = true; this.$ajax({ url: this.$ajax.apiUrl(`/sys/user/detail`), method: "get", params: this.$ajax.adornParams({ id: this.dataForm.id }) }).then(({data}) => { console.log('詳情', data); this.dataForm.deptId = data.deptId; this.dataForm.loginName = data.loginName; this.dataForm.phoneNumber = data.phoneNumber; this.dataForm.remark = data.remark; this.dataForm.roleId = data.roleId; this.dataForm.status = data.status; this.dataForm.userName = data.userName; this.dataForm.id = id; this.deptListTreeSetCurrentNode(); }); } } catch(err){ console.log(err) } },