簡體   English   中英

如何避免使用 Google Apps 腳本在循環中出現空 object 錯誤?

[英]How to avoid empty object error in a loop using Google Apps Script?

我正在調用 API 並通過其分頁獲取數據。 但是,當我到達最后一頁時,給我最后一頁的對象是空的,它拋出以下錯誤: TypeError: Cannot convert undefined or null to object此外,我沒有最后一頁的任何數據。

這是我得到的分頁信息:

{"count":100,"total":545,"_links":
{
 "self":{
         "href":"\/candidates?page=0&per_page=100"
        },
"next":{
        "href":"\/candidates?per_page=100"
        },
"last":{
        "href":"\/candidates?page=6&per_page=100"
        }
},

這是我用來獲取數據的代碼:

function allcandidates() {
  const url = "https://api.catsone.com/v3/candidates";
  const params = {
    'muteHttpExceptions': true,
    'method': 'GET',
    'redirect': 'follow',
    'headers': {
      'Content-Type': 'application/json',
      'Authorization': 'Token ' + API_KEY
    }
  };

  let pageNum = 1;
  let lastPgNo;

  let data = {}, output = [];

  do {
    let currentUrl = url + '?' + 'per_page=100' + '&' + 'page=' + pageNum;
    //One of their URL parameter is "per_page", which is 25 result/page and it go up to 100. I'm not sure if the fact that the last page doesn't have all 100 results may result in an error, too.

    const response = UrlFetchApp.fetch(currentUrl, params);
    const respCode = response.getResponseCode();
    if (respCode != 200) {
      Browser.msgBox('The server seems to be temporarily down. Please try again later.');
      return;
    }
    //Gets the last page number
    const getText = response.getContentText();
    const lastPageObj = JSON.parse(getText)['_links']['last'];
    const lastPgVal = Object.values(lastPageObj); //This is where the error occurs
    const lastPgText = lastPgVal.toString();
    lastPgNo = Number(lastPgText.split('?page=').pop().split('&')[0])

    //Gets current page
    const currentPageObj = JSON.parse(getText)['_links']['self'];
    const currentPgVal = Object.values(currentPageObj);
    const nextPgText = currentPgVal.toString();
    var currentPgNo = Number(nextPgText.split('?page=').pop().split('&')[0])

    const dataSet = JSON.parse(getText)['_embedded']['candidates'];
    for (let i = 0; i < dataSet.length; i++) {
      data = dataSet[i];
      output.push([data.id]);
    }
    pageNum = pageNum + 1;
  } while (pageNum <= lastPgNo);
}

您可以使用if語句並continue IE替換

const lastPgVal = Object.values(lastPageObj);

經過

if(lastPageObj){
  const lastPgVal = Object.values(lastPageObj);
} else {
  continue;
}

另一種選擇是使用try...catch

資源

單擊此處: https://smurfmania.com/kda-akali-prestige-edition/在此處輸入鏈接描述

尋找購買英雄聯盟帳戶的最佳地點? SmurfMania 隨時為您提供幫助,我們有最優惠的價格,即時交付。 當您向我們購買 LOL 帳戶時,您將獲得終身保修。 我們也有很多來自滿意客戶的正面評價。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM