Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
Javascript - Loop through API 10 times, although, using the ID of each returned API call as a parameter for the NEXT api call

I am trying to make 10 API calls to the reddit API to get a users most recent comments.

Basically, Reddit uses a parameter 'after' in the URI to get the next page. So basically, if there is some dummy example comment data below, I need the LAST ID.

Example.

API Call: https://www.reddit.com/user/USERNAME/comments.json?limit=3

returns:

{
   id: 'd4gf125',
   comment: 'blah blah blah'
},
{
   id: 'dag42ra',
   comment: 'blah blah blah'
},
{
   id: 'hq6ir3j', // I need this ID right here, the LAST in the list for the next API call
   comment: 'blah blah blah'
},

Then, another API call needs to be made directly AFTER the previous, using the ID as a parameter.

API Call:

`https://www.reddit.com/user/USERNAME/comments.json?limit=3&after=tl_hq6ir3j`

This will run 10 times, which will get 10 pages, so in total, 30 results.

I have tried using this for loop but as for loops are not asynchronous, I cannot change the variable 'lastID' in time.

First attempt:

const handleSubmit = async () => {
    setLoading(true);
    axios.get(`${apiUrl}user/${username}/about.json`).then((res) => {
      setUserData({
        about: res.data.data,
      });
      axios
        .get(`${apiUrl}user/${username}/comments.json?limit=100`)
        .then((res) => {
          let data = res.data.data.children;
          let lastItem = data[data.length - 1];
          for (i = 0; i < 10; i++) {
            axios
              .get(
                `${apiUrl}comments/${lastItem.data.id}/comments.json?limit=100&after=tl_${lastItem}`
              )
              .then((res) => {
                lastItem =
                  res.data.data.children[res.data.data.children.length - 1];
              });
          }
        });
    });
  };

If you need some example REAL data, see the link below:

https://www.reddit.com/user/bulkorcut99/comments.json?limit=1000&after=t1_hq6ir3j
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

To do async things in sequence, chain promises together with then(). The generic form looks like ths...

let promise = /* starting promise */
for (/* loop stuff */) {
  promise = promise.then(/*another promise*/)
}

Refactoring your code to make this more clear...

function getAbout(username) {
  return axios.get(`${apiUrl}user/${username}/about.json`).then(res => {
    return res.data.data
  });
}

function getComment(username, afterId) {
  const url = `${apiUrl}comments/${lastItem.data.id}/comments.jsonlimit=100`;
  if (afterId) url += `&after=tl_${afterId}`;
  return axios.get(url).then(res => res.data.data);
}

// create a chain of promises to get comments, pushing results as we go
function getComments(username, results) {
  let promise = getComment(username);
  for (let i=0; i<10; i++) {  // not sure why 10 here... from the OP
    promise = promise.then(data => {
      results.push(data);
      const lastChild = data.children[data.children.length-1];
      return getComment(username, lastChild.id);
    });
  }
  return promise;
}

const handleSubmit = async () => {
  setLoading(true);
  return getAbout(username).then(data => {
    setUserData({ about: data });
  }).then(() => {
    let comments = [];
    return getComments(username, comments).then(() => comments)
  }).then(comments => {
    // comments is the result from all of the get comments calls
  })
}

The real API might stop finding comments in fewer than 10 calls. If so, rather than looping to 10, you'd loop until the results were empty or whatever condition indicates there are no more.

about 4 years ago · Juan Pablo Isaza Report

0

You can simply await each of your axios.get calls in your for loop. To do so you can do something like this:

const handleSubmit = async () => {
    setLoading(true);
    axios.get(`${apiUrl}user/${username}/about.json`).then((res) => {
      setUserData({
        about: res.data.data,
      });
      axios
        .get(`${apiUrl}user/${username}/comments.json?limit=100`)
        .then(async (res) => {
          let data = res.data.data.children;
          let lastItem = data[data.length - 1];
          for (i = 0; i < 10; i++) {
            var {data} = await axios
              .get(`${apiUrl}comments/${lastItem.data.id}/comments.json?limit=100&after=tl_${lastItem}`)
            lastItem = data.data.children[data.data.children.length - 1];
          }
        });
    });
  };
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!