0

I want to access variable "gender" in function(data) and then display in an alert outside function(data).

var gender = "";

  fetch('https://randomuser.me/api/?results=10')
  .then(function(response) { return response.json(); })
  .then(function(data) {

 //console.log(data.results[0].gender);
gender = data.results[0].gender;

  })
  .catch(function(error) {
    console.log(error);
  });

  alert(gender);

1 Answers1

1

Since the code which gets gender is asynchronous (based on promises), the alert will be executed before the promise is resolved and gender is retrieved. You should therefore move the alert to inside the function(data) so it executes after genderis assigned.

  • yes, thank you. but i want to assign value to 'gender' and use its variable to outside the 'function(data)'. what can i do? – peterDalis. st Mar 12 '18 at 15:38
  • Don't think of it as just a function that you're done with once it's completed the one thing it was meant to do. Think of it as a continuing process of tasks executed one after another, each successive task depending upon the result from the previous one. Anything done outside the promise chain doesn't wait for the promises to complete, it just executes as soon as possible. I don't know what you want to do with `gender` once you've retrieved it - I'm guessing it's a lot more than just displaying it in a message box. –  Mar 12 '18 at 18:10