0

Why would the variable 'display' here go out of scope and how can I fix it? It prints the proper value within the .then, but as soon as I get to the console log, it is undefined. Is there a way to store the value I get from that promise so I can access it later?

let display;

const user = firebase.getCurrentUser()
  .then(values => {
    console.log("values:",values['email']);
    display = values['email'];
    return display;
  })

console.log("Display is", display);
sevan
  • 51
  • 2
  • You declared `display` in the global scope. Therefore it's gonna be accessible everywhere. – Carl Edwards Feb 02 '20 at 18:59
  • It doesn't go out of scope, you're just trying to read it before you've assigned a value to it. – Quentin Feb 02 '20 at 19:01
  • That's how Promises work in JS. The display value will be undefined at the last line, since the display inside the `then` clause (async) will run after the last line. The only place you can access the value is inside the then – Kostas Minaidis Feb 02 '20 at 19:01
  • You can achieve something similar to what you are trying to do in your code, using async/await: https://jsfiddle.net/hxrbyc28/ Just make sure you understand the concepts of Asynchronous programming, Promises and Async/Await in JavaScript. – Kostas Minaidis Feb 02 '20 at 19:04

0 Answers0