Search code examples
javascriptnode.jsarrayses6-promise

I got the result of an array of links using promise.all, How can I count the links in the array?


function validateAndCountLinks(arrayLinks) {
  let promises = arrayLinks.map((aLink) =>
    fetch(aLink)
      .then((response) => {
        return {
          url: response.url,
          status: response.status,
          text: response.statusText,
        };
      })
      .catch((error) => {
        return { error: error.message };
      })
  );
  return Promise.all(promises).then((result) => result);
}

Solution

  • If your goal is to check an array of links to see that they return a successful status and return the count, you should use the Response.ok property.

    For example

    return Promise.all(arrayLinks.map(link => fetch(link)))
      .then(responses => responses.filter(({ ok }) => ok).length)
    

    I would not bother catching any failed fetch promises as that typically indicates a much bigger problem (eg networking error, invalid permissions, etc) which you would want to filter up to the caller for proper error handling.

    validateAndCountLinks(links).then(count => {
      console.log(`${count} valid links`)
    }).catch(err => {
      console.error('Networking issue', err)
    })