简体   繁体   English

如何避免使用 Google Apps 脚本在循环中出现空 object 错误?

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

I'm calling an API and getting data going through its pagination.我正在调用 API 并通过其分页获取数据。 When I get to the last page, though, the obejct giving me the last page is empty and it's throwing the following error: TypeError: Cannot convert undefined or null to object Besides, I don't any data from that last page.但是,当我到达最后一页时,给我最后一页的对象是空的,它抛出以下错误: TypeError: Cannot convert undefined or null to object此外,我没有最后一页的任何数据。

Here's the pagination information I get:这是我得到的分页信息:

{"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"
        }
},

Here's the code I'm using to get the data:这是我用来获取数据的代码:

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);
}

You might use an if statement and continue .您可以使用if语句并continue IE replace IE替换

const lastPgVal = Object.values(lastPageObj);

by经过

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

Another option is to use try...catch另一种选择是使用try...catch

Resources资源

Click here: https://smurfmania.com/kda-akali-prestige-edition/ enter link description here单击此处: https://smurfmania.com/kda-akali-prestige-edition/在此处输入链接描述

Looking for the best place to buy League of Legends Accounts?寻找购买英雄联盟帐户的最佳地点? SmurfMania is here to help, We have the best prices, instant delivery. SmurfMania 随时为您提供帮助,我们有最优惠的价格,即时交付。 and lifetime warranty when you buy LOL accounts with us.当您向我们购买 LOL 帐户时,您将获得终身保修。 We also have many positive reviews from satisfied customers.我们也有很多来自满意客户的正面评价。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM