小谢第22问:for循环中的异步事件

如果在for循环中写一个函数,然后等待for循环中的函数结束后再进行下一步函数请求,再js中,我们显然要进行同步处理,可以用async await进行处理,如下方代码:

场景:因为要for 循环后才执行this.gettable这个函数,因此用await将api函数变为同步,等待for循环执行结束后再执行this.gettable

async confirmAlarm() {
                // for(let i = 0; i < this.multipleSelection.length; i++){
                //     this.multipleSelection[i].confirmType != 'UNCHECKED';
                // }
                if (this.multipleSelection.length === 0) {
                    this.$message({
                        message: '请选择告警!',
                        type: 'warning'
                    });
                } else {
                    if (this.autoChecked) {
                        this.$message({
                            message: '已启用告警自动确认,不支持手动确认!',
                            type: 'warning'
                        });
                    } else {
                        let params = this.queryArr;
                        for (let i = 0; i < this.multipleSelection.length; i++) {
                            await api.confirmAlarm(params[i]).then(res => {
                                if (res.code == 0) {
                                    this.$message({
                                        message: '确认' + this.multipleSelection[i].extraJson.devName + '告警成功!',
                                        type: 'success'
                                    });
                                } else { 
                                    this.$message({
                                        message: res.message,
                                        type: 'error'
                                    }); 
                                }
                            });
                        }
                        this.getTable();
                    }
                }
            },

 

posted @ 2020-06-10 09:09  优雅的小谢  阅读(338)  评论(0编辑  收藏  举报
Live2D