繁体   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