0

I have an API request and my goal here is to return an array of objects with selected data.

axios.get(collectionsUrl, options)
  .then(function (response) {
    articles = (response.data.articles.items);
    const articleData = [];

    articles.map( article => {
        axios.get(`https://docsapi.helpscout.net/v1/articles/${article.id}`, options)
          .then(function (response) {
          const articleName = response.data.article.slug;
          const articleHtml = response.data.article.text;

          articleData.push({ name : articleName, "HTML" : articleHtml });

        })
          .catch(error => console.error(error));
      });
      console.log(articleData);
    })
  .catch(error => console.error(error));

If I console log within the map method I can see the objects being created as expected. However these aren't getting pushed onto my empty articleData array. I suspect some sort of async issue, but I'm still just learning Javascript and can't quite work out why.

  • 1
    Yep, async issue. When you output the array, the `then` call back has not been called yet. That will only happen when the current call stack has run to completion. – trincot Sep 02 '20 at 21:15
  • 1
    On a side note, it's generally considered bad form to use `.map()` without storing its [returned value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Return_value). If you're using it in this way, you should replace its usage with a loop or [`Array.prototype.forEach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach). – zcoop98 Sep 02 '20 at 21:15

0 Answers0