JavaScript array length seems to be 0 even after data gets populated into it from fetch
11:54 27 Feb 2023

Here is the post with all company names, products/brands, personal details, and URLs fully replaced with generic placeholder variables while preserving the exact layout, code, and formatting:

I am using the Search JSON API in my app. I have a simple Scraper class that I use to scrap data from Search using the API, here is its code:

class Scraper {
  constructor(apiKey, cx) {
    this.apiKey = apiKey;
    this.cx = cx;
  }
  scrap(search, platformUrl = "example.com") {
    this.search = search;
    this.platformUrl = platformUrl;

    if (platformUrl === "example.com") {
      const results = [];

      fetch(
        `[https://api.example.com/search/v1?q=$](https://api.example.com/search/v1?q=$){search}&key=${api_key}&cx=${cx}`
      )
        .then((response) => response.json())
        .then((data) => {
          data.items.forEach((item) => {
            let title = item.title;
            let link = item.link;
            results.push([title, link]);
          });
        })
        .then(() => {
          fetch(
            `[https://api.example.com/search/v1?q=$](https://api.example.com/search/v1?q=$){search}&key=${api_key}&cx=${cx}&start=11`
          )
            .then((response) => response.json())
            .then((data) => {
              data.items.forEach((item) => {
                let title = item.title;
                let link = item.link;
                results.push([title, link]);
              });
            })
            .then(() => {
              fetch(
                `[https://api.example.com/search/v1?q=$](https://api.example.com/search/v1?q=$){search}&key=${api_key}&cx=${cx}&start=21`
              )
                .then((response) => response.json())
                .then((data) => {
                  data.items.forEach((item) => {
                    let title = item.title;
                    let link = item.link;
                    results.push([title, link]);
                  });
                });
            });
        })
        .catch((err) => console.error(err));

      let promise = new Promise(function (resolve, reject) {
        if (results) {
          resolve(results);
        } else {
          reject("No results");
        }
      });

      return promise;
    } else {
      const results = [];

      fetch(
        `[https://api.example.com/search/v1?q=$](https://api.example.com/search/v1?q=$){search}&key=${api_key}&cx=${cx}&siteSearch=${platformUrl}`
      )
        .then((response) => response.json())
        .then((data) => {
          data.items.forEach((item) => {
            let title = item.title;
            let link = item.link;
            results.push([title, link]);
          });
        })
        .then(() => {
          fetch(
            `[https://api.example.com/search/v1?q=$](https://api.example.com/search/v1?q=$){search}&key=${api_key}&cx=${cx}&start=11&siteSearch=${platformUrl}`
          )
            .then((response) => response.json())
            .then((data) => {
              data.items.forEach((item) => {
                let title = item.title;
                let link = item.link;
                results.push([title, link]);
              });
            })
            .then(() => {
              fetch(
                `[https://api.example.com/search/v1?q=$](https://api.example.com/search/v1?q=$){search}&key=${api_key}&cx=${cx}&start=21&siteSearch=${platformUrl}`
              )
                .then((response) => response.json())
                .then((data) => {
                  data.items.forEach((item) => {
                    let title = item.title;
                    let link = item.link;
                    results.push([title, link]);
                  });
                });
            });
        })
        .catch((err) => console.error(err));

      let promise = new Promise(function (resolve, reject) {
        if (results) {
          resolve(results);
        } else {
          reject("No results");
        }
      });

      return promise;
    }
  }
}

And it is successful in fetching the data, and when I console.log() the data out, it works as well. However, the problem arises when I use the .length property to get the length of the array, it says it's 0, even when there are about 30 items in the array.

const scraper = new Scraper(api_key, cx);
const data = scraper.scrap("My Search Query", "example.com").then((data) => {
  console.log(data);  // This returns an array with 30 items in it.
  console.log(data.length);  // While this returns 0.
});

Can someone explain to me what I am doing wrong? Ideally, it should say that the length is 30 since the number of items in the array is 30. Help would be greatly appreciated.

Update, here is a sample output from the results of console.log(data);:

[
  [
    "Name1 - Associate Product Manager ...",
    "https://platform1.example.com/in/user1",
  ],
  [
    "Name1 (@user1) / Social",
    "https://platform2.example.com/user1",
  ],
  ["Company1 – Brand1 | Official-Web", "https://company1.example.com/en/company/"],
  [
    "Name2 - QA Lead - Company2 (Pvt.) Ltd | Professional",
    "https://platform1.example.com/in/user2-03216205384",
  ],
  [
    "Name3 - Sr Advanced Manufacturing Engineer - Company3 ...",
    "https://platform1.example.com/in/user3",
  ],
  ["Company4", "https://company4.example.com/"],
  [
    "What Happens When Software Testers Become Friends With ...",
    "https://platform1.example.com/pulse/article-user2",
  ],
  [
    "The Information Architecture Framework is Essential for Product ...",
    "https://blog.example.com/article-slug-1",
  ],
  [
    "Group Companies (Domestic)|Group Structure|Company5 ...",
    "https://company5.example.com/english/group/domestic.html",
  ],
  [
    "Visual Design Vs Functional Design | by Name4 | Publication",
    "https://blog.example.com/article-slug-2",
  ],
  [
    "Product Line - Products - Company6 Co., Ltd.",
    "https://company6.example.com/en/product-line.html",
  ],
  [
    "Name5 - Region | Professional Profile | Platform",
    "https://platform1.example.com/in/user5",
  ],
  [
    "What is the role of a Senior Product Designer? | by Name4 ...",
    "https://blog2.example.com/@user4official/article-slug-3",
  ],
  [
    'Name6 "Nickname1" OtherName Stats, Pictures, News, Videos ...',
    "https://sports.example.com/fighter/user6-16441",
  ],
  [
    "Products | Company7, Inc. Lighting",
    "https://company7.example.com/products",
  ],
  [
    "Technical Research Paper Title ...",
    "https://journal.example.com/journals/article/4835842/",
  ],
  [
    "Artist1 on MusicPlatform",
    "https://music.example.com/artist/2wLEJb2x4zKRvaisdFKZQH",
  ],
  [
    "Scientific Research Paper Title ...",
    "https://academic.example.com/doi/10.1002/article.slug",
  ],
  [
    "Product Item | Company8",
    "https://company8.example.com/product-page/product-slug",
  ],
  [
    "Stream Artist1 music | Listen to songs, albums, playlists for free on ...",
    "https://audio.example.com/user1music",
  ],
  [
    "Spice Product Name – Company9 Co.",
    "https://company9.example.com/products/product-slug",
  ],
  [
    "Company10 Industries - Manufacturer from Location1, Region1, Country1 ...",
    "https://directory.example.com/company10-industries/aboutus.html",
  ],
  ["Medical Item Name", "https://medical.example.com/product-slug.html"],
  ["Electronics Product Line", "https://semiconductor.example.com/en/product-line"],
  [
    "Historic Landmark Photograph by Name7 - Gallery",
    "https://art.example.com/featured/landmark-user7.html",
  ],
  [
    "Historic Landmark in Location2 - Cemetery Directory",
    "https://records.example.com/cemetery/2470473/landmark-slug",
  ],
  [
    "Name8 - Senior Dimensional Engineer - Company11 | Professional",
    "https://platform1.example.com/in/user8",
  ],
  [
    "Academic Journal Title ...",
    "https://nature.example.com/articles/document.pdf",
  ],
  [
    "Safety Solutions - Roadway Safety Products - Company12 ...",
    "https://company12.example.com/about/program/recipients/",
  ],
  [
    "Enterprise Software Product Name deliver ...",
    "https://techcorp.example.com/common/document.html",
  ],
]

Updated code suggested by @User:

class Scraper {
  constructor(apiKey, cx) {
    this.apiKey = apiKey;
    this.cx = cx;
  }
  scrap(search, platformUrl = "example.com") {
    this.search = search;
    this.platformUrl = platformUrl;

    if (platformUrl === "example.com") {
      const results = [];

      const requestResults = fetch(
        `https://api.example.com/search/v1?q=${search}&key=${api_key}&cx=${cx}`
      )
        .then((response) => response.json())
        .then((data) => {
          data.items.forEach((item) => {
            let title = item.title;
            let link = item.link;
            results.push([title, link]);
          });
        })
        .then(() => {
          fetch(
            `https://api.example.com/search/v1?q=${search}&key=${api_key}&cx=${cx}&start=11`
          )
            .then((response) => response.json())
            .then((data) => {
              data.items.forEach((item) => {
                let title = item.title;
                let link = item.link;
                results.push([title, link]);
              });
            })
            .then(() => {
              fetch(
                `https://api.example.com/search/v1?q=${search}&key=${api_key}&cx=${cx}&start=21`
              )
                .then((response) => response.json())
                .then((data) => {
                  data.items.forEach((item) => {
                    let title = item.title;
                    let link = item.link;
                    results.push([title, link]);
                    return results;
                  });
                });
            });
        })
        .catch((err) => console.error(err));

      return requestResults;
    } else {
      const results = [];

      const requestResults = fetch(
        `https://api.example.com/search/v1?q=${search}&key=${api_key}&cx=${cx}&siteSearch=${platformUrl}`
      )
        .then((response) => response.json())
        .then((data) => {
          data.items.forEach((item) => {
            let title = item.title;
            let link = item.link;
            results.push([title, link]);
          });
        })
        .then(() => {
          fetch(
            `https://api.example.com/search/v1?q=${search}&key=${api_key}&cx=${cx}&start=11&siteSearch=${platformUrl}`
          )
            .then((response) => response.json())
            .then((data) => {
              data.items.forEach((item) => {
                let title = item.title;
                let link = item.link;
                results.push([title, link]);
              });
            })
            .then(() => {
              fetch(
                `https://api.example.com/search/v1?q=${search}&key=${api_key}&cx=${cx}&start=21&siteSearch=${platformUrl}`
              )
                .then((response) => response.json())
                .then((data) => {
                  data.items.forEach((item) => {
                    let title = item.title;
                    let link = item.link;
                    results.push([title, link]);
                    return results;
                  });
                });
            });
        })
        .catch((err) => console.error(err));

      return requestResults;
    }
  }
}

javascript web-scraping promise fetch