1

Running the below code on the console, I get an array of objects.

fetch('https://api.github.com/users/chriscoyier/repos')
  .then(response => response.json())
  .then(data => {
    // Here's a list of repos!
    console.log(data)
  });

How can I access the data later? For example if I wanted to console.log the data[0].archive_url, after the promise has resolved? But that gives an error "Uncaught ReferenceError: data is not defined". How do I access that array of objects?

console

userden
  • 1,615
  • 6
  • 26
  • 50

1 Answers1

1
var myGlobalVar;

fetch('https://api.github.com/users/chriscoyier/repos')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    myGlobalVar = data;
  });

Once this request has finished (once you see the console output), the data is now available in the variable myGlobalVar for you to play around with on the console. You could also use your browser's debugger to set a breakpoint in the callback function and have direct access to data from there.

Note that this won't work in actual code, this is only useful for the interactive console: How do I return the response from an asynchronous call?

deceze
  • 510,633
  • 85
  • 743
  • 889