在写线上运维平台中的表单处理逻辑时,遇到困扰的地方
//验证表单 checkForm(){ return new Promise((resolve, reject) => { var checkResult=true this.$refs[‘businessInfo‘].validate((valid) => { if (valid) { } else { this.$Message.error(‘请检查业务及归属信息‘); checkResult=false } console.log(‘1: ‘+checkResult) }) this.$refs[‘topicInfo‘].validate((valid) => { if (valid) { } else { this.$Message.error(‘请检查topic信息‘); checkResult=false } console.log(‘2: ‘+checkResult) }) // 校验topic名称 let that=this that.topicTotal.forEach(function(item,i){ // forEach中对this进行了重定向,所以需要将this赋值给其他变量才能引用 if(that.topicInfo.topicName===item.topicName){ that.$Message.error(‘该topic已存在,请重新命名‘) checkResult=false } console.log(‘3: ‘+checkResult) }) console.log(‘4: ‘+checkResult) if(checkResult){ resolve(true) }else{ resolve(false) } }) }, //切换页面 changeCurrentPage(page) { this.defaultPage = page; switch (page) { case 1: this.$refs.flowApply.changePage(page) this.changLength() break case 2: { this.checkForm().then(res=>{ console.log(‘5:‘+res) // res=true if (res){ this.$refs.flowApply.changePage(page) this.businessInfo.applicant = this.uuapUserName this.newTopicApplyInfo.businessInfo=this.businessInfo this.newTopicApplyInfo.topicInfo=this.topicInfo } }) break } default: { this.$refs.flowApply.changePage(page) } } return false },
上面的逻辑并没有按照我预想的顺序由上至下执行,而是
是因为js维护两个队列,分别放置宏任务和微任务,宏任务优先级高于微任务
代码中的逻辑事件任务类别
逻辑编号 | 具体逻辑 | 任务类别 | 备注 |
1 |
this.$refs[‘topicInfo‘].validate((valid) => |
微任务1 | |
2 |
this.$refs[‘topicInfo‘].validate((valid) => { |
微任务2 | |
3 | script中的正常代码:遍历逻辑 | 宏任务1 | |
4 | script代码:console | 宏任务2 | |
5 |
this.checkForm().then(res=>{
|
另一函数中的微任务1 | promise.then |
预期的执行顺序是1,2,3,4,5
更正为
- 将宏任务1和宏任务2放到微任务2中
//验证表单 checkForm(){ return new Promise((resolve, reject) => { var checkResult=true this.$refs[‘businessInfo‘].validate((valid) => { if (valid) { } else { this.$Message.error(‘请检查业务及归属信息‘); checkResult=false } console.log(‘1: ‘+checkResult) }) this.$refs[‘topicInfo‘].validate((valid) => { if (valid) { } else { this.$Message.error(‘请检查topic信息‘); checkResult=false } console.log(‘2: ‘+checkResult) // 校验topic名称 let that=this that.topicTotal.forEach(function(item,i){ // forEach中对this进行了重定向,所以需要将this赋值给其他变量才能引用 if(that.topicInfo.topicName===item.topicName){ that.$Message.error(‘该topic已存在,请重新命名‘) checkResult=false } }) console.log(‘3: ‘+checkResult) console.log(‘4: ‘+checkResult) if(checkResult){ resolve(true) }else{ resolve(false) } }) }) }, //切换页面 changeCurrentPage(page) { this.defaultPage = page; switch (page) { case 1: this.$refs.flowApply.changePage(page) this.changLength() break case 2: { this.checkForm().then(res=>{ console.log(‘5:‘+res) // res=true if (res){ this.$refs.flowApply.changePage(page) this.businessInfo.applicant = this.uuapUserName this.newTopicApplyInfo.businessInfo=this.businessInfo this.newTopicApplyInfo.topicInfo=this.topicInfo } }) break } default: { this.$refs.flowApply.changePage(page) } } return false },
达到了预期