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) => {})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM