• Promise以及Promise.all的简单用法


    当你请求多个数据,相统一处理的时候,假设有两个单独的接口获取页面数据,两接口使用Promise处理是互不影响:

    1. //基础信息获取
    2. getPlantProductReportInfoItems() {
    3. return new Promise((resolve, reject) => {
    4. treeData[0].children = [];
    5. getPlantProductReportInfoItems({})
    6. .then(({ data: res }) => {
    7. console.log('res', res);
    8. if (res.code !== 0) {
    9. this.roleLoading = false;
    10. this.$message.config({
    11. maxCount: 1,
    12. });
    13. this.$message.destroy();
    14. return this.$message.error(res.msg);
    15. }
    16. if (JSON.stringify(res.data) != '{}') {
    17. for (let item in res.data) {
    18. let arrobj = {
    19. key: item,
    20. title: res.data[item],
    21. children: [],
    22. // disabled: !item.includes(children) ? false : true
    23. };
    24. treeData[0].children.push(arrobj);
    25. }
    26. }
    27. resolve();
    28. })
    29. .catch((error) => {
    30. //失败调用reject函数
    31. reject(error);
    32. });
    33. }).then((data) => {});
    34. },
    35. //统计数据
    36. getPlantProductReportDataItems() {
    37. return new Promise((resolve, reject) => {
    38. treeData[1].children = [];
    39. getPlantProductReportDataItems({
    40. dataType: this.dataForm.selectTime2Type,
    41. })
    42. .then(({ data: res }) => {
    43. console.log('res', res);
    44. if (res.code !== 0) {
    45. this.roleLoading = false;
    46. this.$message.config({
    47. maxCount: 1,
    48. });
    49. this.$message.destroy();
    50. return this.$message.error(res.msg);
    51. }
    52. if (JSON.stringify(res.data) != '{}') {
    53. let arrobj = {};
    54. for (let item in res.data) {
    55. arrobj = {
    56. key: item,
    57. title: res.data[item],
    58. children: [],
    59. // disabled: !item.includes(children) ? true : false
    60. };
    61. treeData[1].children.push(arrobj);
    62. }
    63. }
    64. resolve();
    65. })
    66. .catch((error) => {
    67. //失败调用reject函数
    68. reject(error);
    69. });
    70. }).then((data) => {});
    71. },

    使用Promise.all时,每一个promise对象都会返回自身。这样处理比之前一个个的调用接口速度快些。

    1. //设置弹窗
    2. handleSettingItems() {
    3. Promise.all([this.getPlantProductReportDataItems(),this.getPlantProductReportInfoItems()]).then(() => {
    4. transferDataSource = [];
    5. flatten(treeData);
    6. this.dataSource = transferDataSource;
    7. console.log("this.dataSource", this.dataSource);
    8. this.settingVisible = true;
    9. })
    10. },

  • 相关阅读:
    RHCSA1
    java并发编程,lock(),trylock(),lockInterruptibly()的区别
    Java测试框架:分享常用的Java测试框架,如JUnit, TestNG等,包括单元测试,集成测试,性能测试等
    产品经理考个 PMP 有用吗?
    【EI/SCOPUS会议征稿】第二届环境遥感与地理信息技术国际学术会议(ERSGIT 2023)
    DRF统一返回格式
    Git学习笔记 - 搭建GitLab服务器与Idea集成GitLab
    Java面试之JavaWeb常用框架(offer 拿来吧你)
    一文带你走进网络编程
    HTTP1.0,1.1,2.0
  • 原文地址:https://blog.csdn.net/XU441520/article/details/125621517