0

If I try to console.log the array 'profiles' I only get results when in the fetch code block, outside fetch code block the array is empty. Anyone has an idea how this comes?

I removed some variables to reduce the code but the problem only takes place outside of the fetch code block, in other words, outside of the function getTinderProfiles().

While I'm clearly storing the data of the person object in the array 'profiles' I can not think of a problem to log the data of that array.

let url = 'https://randomuser.me/api/?results=11';
let profiles = [];
let Person = new Object();

function getTinderProfiles() {
  fetch(url)
    .then(function (response) {
      return response.json();
    })
    .then(function (tinderUsers) {

  // Get 10 users and put data in object
  let randomUser = tinderUsers.results;
  for (let i = 0; i < randomUser.length; i++) {
    Person = {
      picture: randomUser[i].picture.large,
      name: randomUser[i].name.first + ' ' + randomUser[i].name.last,
      age: 'Age: ' + randomUser[i].dob.age,
      location: randomUser[i].location.city + ' ' + randomUser[i].location.postcode + '<br>' + randomUser[i].location.street,
    }
    // console.log(JSON.stringify(Person));

    // Add fetched persons to profiles array
    function pushToProfiles() {
      profiles.push(Person);
      console.log(profiles);
    }
    pushToProfiles();
  
  console.log(profiles[0]); // RESULTS !!!

});
}
 getTinderProfiles();
console.log(profiles); NO RESULTS !!!
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Bruno
  • 11
  • 2
  • Fetch is asynchronous. The code inside the promise will execute after the fetch finishes; the code after the initial call will (most likely) run before it. – puddi Oct 19 '18 at 19:31
  • Also, I saw this question literally after [this other one](https://stackoverflow.com/questions/52898738/why-cant-i-access-a-global-array-in-a-then-scope#52898738) which is the exact same gind of problem. – VLAZ Oct 19 '18 at 19:32
  • Fetch runs asynchronously, so when you are trying to log your results they don't exist yet. `getTinderProfiles().then(profiles => console.log(profiles))` will give you results. – D Lowther Oct 19 '18 at 19:37

2 Answers2

-1

The getTindersProfile function you are calling contain an asynchronous function (fetch).

Meaning the system will only make a network call to the url but will not wait for any response (asynchronous). So the function will end and continue executing the next function which is the console.log.

The system will only execute the function in the then (promise) only when the response is ready.

Therefore the console.log is executed before the loop that creates and fill the profile array.

To fix your issue, simply create a callback that should be executed only when the response is ready.

let url = 'https://randomuser.me/api/?results=11';
let profiles = [];
let Person = new Object();

function getTinderProfiles(callback) {
  fetch(url)
    .then(function (response) {
      return response.json();
    })
    .then(function (tinderUsers) {

  // Get 10 users and put data in object
  let randomUser = tinderUsers.results;
  for (let i = 0; i < randomUser.length; i++) {
    Person = {
      picture: randomUser[i].picture.large,
      name: randomUser[i].name.first + ' ' + randomUser[i].name.last,
      age: 'Age: ' + randomUser[i].dob.age,
      location: randomUser[i].location.city + ' ' + randomUser[i].location.postcode + '<br>' + randomUser[i].location.street,
    }
    // console.log(JSON.stringify(Person));

    // Add fetched persons to profiles array
    function pushToProfiles() {
      profiles.push(Person);
      console.log(profiles);
    }
    pushToProfiles();

  console.log(profiles[0]); // RESULTS !!!
  // Call the call back function here
   callback();

});
}
 getTinderProfiles(function(){
     console.log(profiles); // RESULTS AVAILABLE !!!
 });
Mzndako
  • 72
  • 1
  • 4
  • Mzndako, totally did the trick! Fetch/promises is all kind of new to me but we have to implement them for school projects. This problem is solved, on to the next one :) Thanks a lot sir. – Bruno Oct 19 '18 at 21:40
-1

As getTinderProfiles is asynchronous you can use a callback function to use it results. You call the callback function when you have processed the results of your fetch. The important thing is to declare profiles inside getTinderProfiles. If you declare it outside of getTinderProfiles it will always be empty. Your code is missing a brace closing the function (tinderUsers)

function getTinderProfiles(useProfiles) {
    let profiles = [];
    fetch(url).then(function (response) {
        return response.json();
    }).then(function (tinderUsers) {
      // Get 10 users and put data in object
        let randomUser = tinderUsers.results;
        for (let i = 0; i < randomUser.length; i++) {
            Person = {
                picture: randomUser[i].picture.large,
                name: randomUser[i].name.first + ' ' + randomUser[i].name.last,
                age: 'Age: ' + randomUser[i].dob.age,
                location: randomUser[i].location.city + ' ' + randomUser[i].location.postcode + '<br>' + randomUser[i].location.street,
            }
         profiles.push(Person);    
         }
      useProfiles(profiles)
      });
    }


function useProfiles(profiles){
    console.log(profiles);
}
Stephen O'Connor
  • 1,465
  • 1
  • 10
  • 20
  • Hi, Steve thanks a lot for the reply! :) Trying it out at the moment but getting a little error in console, saying "Uncaught (in promise) TypeError: useProfiles is not a function". I implemented your code as supposed to. Is there anything I must be aware of? The fetch/promise things are new to me but must implement them in schoolproject. Thanks in advance! – Bruno Oct 19 '18 at 21:09