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

6
  • console.log(data[0].archive_url) works fine for me. jsfiddle.net/dyspkd12 Commented Aug 1, 2017 at 7:42
  • Assign data to a global variable. Commented Aug 1, 2017 at 7:43
  • @Adriani6 I would like to access the data after the promise has resolved. That only works if I put it in the fetch request immidietly. Commented Aug 1, 2017 at 7:50
  • @deceze Could you make an example, please? Commented Aug 1, 2017 at 7:51
  • Not reproducable. @Adriani6's snippet works perfectly fine. Commented Aug 1, 2017 at 7:54

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.