一、Promise.all

简述

Promise.all可以将多个Promise实例包装成一个新的Promise实例。同时,成功和失败的返回值是不同的,成功的时候返回的是一个结果数组,而失败的时候则返回最先被reject失败状态的值。Promse.all在处理多个异步处理时非常有用,比如说一个页面上需要等两个或多个ajax的数据回来以后才正常显示,在此之前只显示loading图标。
注意: Promise.all成功结果数组里的数据顺序和Promise.all接收到的数组顺序是一致的。 所以在前端开发请求数据的过程中,偶尔会遇到发送多个请求并根据请求顺序获取和使用数据的场景,使用Promise.all毫无疑问可以解决这个问题。

举例

let P1 = new Promise((resolve, reject) => {
  resolve('成功')
})

let P2 = new Promise((resolve, reject) => {
  resolve('success')
})

let P3 = Promse.reject('失败')

Promise.all([P1, P2]).then((result) => {
  console.log(result)     //控制台打印结果['成功了', 'success']
}).catch((error) => {
  console.log(error)
})

Promise.all([P1,P3,P2]).then((result) => {
  console.log(result)
}).catch((error) => {
  console.log(error)      // 控制台打印结果 '失败'
})

实战

这里实现的功能是调用后台接口返回数据实现全选反选

在这里插入图片描述

<template>
  <div class="table-container-wapper" id="apps-permission" v-loading="isTableLoading">
    <div class="func-btn">
      <el-button @click="selectInvert" class="invert">反选</el-button>
      <span class="cur">/</span>
      <el-button @click="selectAll" class="allSelect">全选</el-button>
    </div>
    <div class="choose">
      <div v-for="(item, index) in form" :key="index" class="select-list">
        <el-checkbox  v-model="item.select">{{ item.serviceName }}</el-checkbox>
      </div>
    </div>
    <div class="foot">
      <el-button class="cancel" size="small" @click="$router.back()">取 消</el-button>
      <el-button type="success" size="small" @click="submit">确 定</el-button>
    </div>
  </div>
</template>
<script>

import BaseMixin from "@/mixins/base";
import request from "@/utils/request";
import SETTING from "@/settings";

export default {
  mixins: [BaseMixin],
  data() {
    return {
      clientId: this.$route.query.id,
      form: [],
    };
  },
  created() {
    this.isTableLoading = true
    Promise.all([
      this.getServiceInfo(),
      this.getList()
    ]).then(([form, data]) => {
      let hasArr = data.map(item => item.serviceId)
      form.forEach(item => {
        if(hasArr.includes(item.id)) {
          item.select = true
        }else {
          item.select = false
        }
      })
      this.form = form
      this.isTableLoading = false
    }, _ => { 
      this.isTableLoading = false
    })
  },
  methods: {
    getServiceInfo() {
      return new Promise((resolve, reject) => {
        request({
          url: `${SETTING.IOT_APPLICATION}/serviceInfo`,
          params: {
            page: this.pagination.page - 1,
            size: 1000,
          },
        }).then(
          (res) => {
            if (res.code=== "200") {
              resolve(res.data.content)
            }
            reject()
          },
          (_) => {
            reject()
            this.$message({
              type: "error",
              message: _.message || "查询列表失败",
            });
          }
        );
      })  
    },
    getList() {
      return new Promise((resolve, reject) => {
        request({
          url: `${SETTING.IOT_APPLICATION}/sdkAppServiceRelation/curRights/${this.clientId}`,
        }).then(
          (res) => {
            if (res[SETTING.IOT_THING_MODEL_STATES] === "200") {
              resolve(res.data)
            }
            reject()
          },
          (_) => {
            reject()

            this.$message({
              type: "error",
              message: _.message || "查询列表失败",
            });
          }
        );
      })
    },

    //全选
    selectAll() {
      console.log(111)
      this.form.forEach((item) => {
        item.select = true;
      });
    },
    //反选
    selectInvert() {
      this.form.forEach((item) => {
        item.select = !item.select;
      });
    },
    //提交
    submit() {

      let ids = this.form.filter(item => item.select).map(item => item.id)

      request({
        url: `${SETTING.IOT_APPLICATION}/sdkAppServiceRelation/rights`,
        method: "post",
        data: {
          clientId: this.clientId,
          ids: ids
        }
      }).then(
        (res) => {
          if (res[SETTING.IOT_THING_MODEL_STATES] === "200") {
            this.$message({
              type: "success",
              message: res.msg || res.message ||  "操作成功",
            });

            this.$router.back()
          }
        },
        (_) => {
          reject()

          this.$message({
            type: "error",
            message: _.message || "查询列表失败",
          });
        }
      );
    },
  },
};
</script>
<style lang="scss" scope>
#apps-permission {
  max-width: 1000px;
  .func-btn {
    overflow: hidden;
    margin-top: 10px;
    .invert {
      border: 0px;
      padding: 0;
      float: right;
      font-size: 16px;
    }
    .cur {
      margin-left: 5px;
      margin-right: 5px;
      float: right;
      font-size: 16px;
    }
    .allSelect {
      border: 0px;
      padding: 0;
      float: right;
      font-size: 16px;
    }
  }
  .choose {
    display: flex;
    flex-wrap: wrap;
    .select-list{
      margin-bottom: 12px;
      width: 25%;
    }
  }
  .foot {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
}
</style>

扩展知识:Promise.race,哪个结果快就返回哪个

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐