使用async返回promise<pending>状态的解决

0. 表格初始化数据

有四个分发的子项内容,从父组件这里给出去。因为有异步内容,就在获取组件这一步getPageData()用了async await保证获取数据再继续。然后没想到的是,把data传到子组件后这玩意变为promise的

1. 解决思路

总所周知,是个待定状态,啥也拿不到。所以得从出现这个promise的位置入手,返回,再在子组件中then一下得到data。
参考网页,这位大兄弟博客布局漂亮,问题分析的也很到位!

2. 代码

this.sonConfig是post获取数据的某个参数。
父组件中

  // Get Report Data
    // Mobile is the kind of promise <pending>
    // Async return always is promise statement.
    // It need to translate to normal data structure.
    async getReportData(item) {
      if (Object.keys(this.sonConfig).length) {
        let title = item.option.module;
        let filter = {
          classifyId: this.classifyId,
        };
        let mobile = await new Promise((resolve) => {
          getPageData(filter).then((result) => {
            let data =
              result && result.data && result.data.length
                ? result.data[0].lineBarData
                : null;

              return resolve(data);
            }
          });
        });
        return mobile;
      }
    },

子组件中
父传data给子,子props得到

    // 获取数据
    async getData() {
      // Add staticText
      let summary = this.staticText;
      await this.$emit("get-config", this.config);
      let data = await this.data.then((result) => {
        return result;
      });
      // Transform the String type to Float
      data.items.forEach((key) => {
        key.value[0] = parseFloat(key.value[0]);
      });

3. 心得

做这个综合获取数据接口的时候,屡屡碰壁,最后遇到promise这里差点就放弃了。还好搜到了非常有用的博客,很感谢别人的帮助,还有自己的坚持!

人生到处知何似,应似飞鸿踏雪泥。
原文地址:https://www.cnblogs.com/lepanyou/p/15562446.html