使用async返回promise 狀態的解決


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這里差點就放棄了。還好搜到了非常有用的博客,很感謝別人的幫助,還有自己的堅持!


免責聲明!

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



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