Promise.all( ) 的使用

一、多个函数等待执行

        //初始化权限列表
        initPermission() {
            return new Promise((resolve, reject) => {
                this.$ajax.get(this.permissionUrl[1], { type: 9 }).then(res => {
                    if (res.code == 200) {
                        console.log(212)
                        this.permissionData = this.$_c.listToTree(res.data, { idKey: 'id', parentKey: 'parent' });
                        resolve(0)//这里一定要加上,否则then和catch都不会执行
                    }
                })
            })
        },

        //初始化操作类型
        initTypeId() {
            return new Promise((resolve, reject) => {
                this.$ajax.get(this.permissionUrl[2]).then(res => {
                    if (res.code == 200) {
                        //1.selfCheckbox的版本
                        // this.typeData = {
                        //     field: 'typeId',
                        //     isShow: true,
                        //     isInline: true,
                        //     children: res.data
                        // }
                        //2.tree的版本
                        this.newtypeData = this.$_c.listToTree(res.data, { idKey: 'id', parentKey: 'parentCode' })
                        console.log(this.form.typeId)
                        resolve(0)
                        // this.$refs.devTypeTree.setCheckedKeys(this.form.typeId)//设置选中
                    }
                })
            })
        },

调用

mounted() {
        this.initRoleList()//初始化下拉角色列表
        Promise.all([
            this.initPermission(),//初始化权限树
            this.initTypeId()//初始化设备类型树
        ]).then(res => {
            console.log(res)
            this.initCheck()//初始化默认选中
        }).catch(function(){
            console.log(0)
        })
    }

注意事项

1.函数里面一定要加上 resolve(0),否则promise.all方法的then和catch都不会执行

 

 

 

二、如果是单个

第一种:

//登陆之前调用退出的接口
async login() {
            this.ruleForm.date = this.expressTimeSelect == '-' ? (this.expressTimeInput * 60) : this.expressTimeSelect
            if(!this.verify()){return false}
            console.log(document.cookie)
            console.log(cookies.get('access_token'))
            await this.$ajax.get(Api.loginOut, { access_token: cookies.get('access_token') })
            this.startLogin()
        },

第二种:

//登录之前掉退出的接口
        async beforeQuit() {
            const res = await this.$ajax.get(Api.loginOut, { access_token: cookies.get('access_token') })
           return res
        },

登陆前调用

 await this.beforeQuit().then((res) => {})

 

posted @ 2020-06-29 17:52  人在路途  阅读(904)  评论(0编辑  收藏  举报