0

I am building an api that receives an array of items then calls a function passing the array as a parameter.

router.post('/api/statuses/:client', function (req, res, next) {
    console.group('FETCHING STATUS CALLS')
    console.log(`In POST /api/statuses/${req.params.client}`);

    let apps = new Array(); //req.query.app ? req.query.app : apps
    if (req.query.app){
        apps.push(app)
    } else {
        apps = ['xyz', 'abc', 'def']
    }
    const env = req.query.env ? req.query.env : 'int'
    getParentApp(apps, env, res)
    console.groupEnd('FETCHING STATUS CALLS')
});

In the getParentApp, I mapped the array and for each item in the aforementioned array, I did a fetch call to receive the information from an API that returns an Object.

function getParentApp(apps, env, res) {
  let hashes = new Array();
  let parent;
  let id = '';
  let pass = ""

  console.group('GETTING PARENT')
  apps.map(app => {
    layer = app.charAt(0)
    appName = app.slice(1)

    console.log(appName, env.toLowerCase(), parent)

    fetch(`https://${env}.api.com/${app}/v1/status?layerOption=${layer}api`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic ' + base64.encode(`${id}:${pass}`)
        }
      }).then(res => res.json())
      .then(data => {
        return data
      }).then(data => hashes.push(data)) // If I change this to a console.log, it returns the expected data. 
      .catch((err) => {
        console.log(err)
      })
    console.log(hashes)
  })

  console.log(hashes)
  console.groupEnd('GETTING PARENT')
}

I tried placing the fetch call in a separate function, which helped to return an object but rather than pushing the next fetch calls' response into the array, it attempts to overwrite it. What am I doing wrong here? Async functions did not work for me, maybe I'm misusing them?

Andreas
  • 21,535
  • 7
  • 47
  • 56
Amer
  • 57
  • 8
  • The `hashes` array is defined inside the same function where you're making the call and pushing the item in to the array. When that function finishes execution, that `hashes` variable is now gone. Do you have a scoping problem here? Should `hashes` be moved outside the function calling for more data? – Brant Jan 10 '20 at 15:56
  • I don't think it's a scoping issue as I am trying to console.log the variable within the function. That being said, I tried moving the hashes variable outside the function, making it a global variable with no luck. – Amer Jan 10 '20 at 16:00
  • If you're not interested in the return value of `.map()` then you shouldn't use it in the first place. – Andreas Jan 10 '20 at 16:04
  • Ofc its not a scoping issue, its an async function issue. – n3ko Jan 10 '20 at 16:07
  • https://www.tutorialspoint.com/es6/es6_promises.htm for more detail. In short: `map` returns before all the `fetch`es finished (because they also returns), so the last console.log calls when the `hashes` object is stil empty. – n3ko Jan 10 '20 at 16:20

0 Answers0