-2
let user;

getCustomer(1)
.then(user => {
    user = user;
    return getTopMovies();
})
.then(movies => {
    //i'll need this variable here but the value is undefined.
    console.log(user);
})

Why i cant get the correct user variable value? even though it should be available cause i defined it as global-scoped variable.

MORA
  • 137
  • 1
  • 8

1 Answers1

-1

The user argument you use in your first then function, is not the user variable, but just a name you give to the getCustomer returned response. Check out how promises work. You can use directly user without passing it as argument to arrow function, I mean:

.then( () => { 
  /* use user variable there*/ 
}    

You can look on w3schools: https://www.w3schools.com/js/js_promise.asp

You have to decide which user you want, the one returned by the promise, or the global variable. The next ".then" function gets arguments from what the previous ".then" returned.

Kris1803
  • 82
  • 5
  • "*You can use directly user without passing it as argument to arrow function*" - no, you can't. Check out how promises work. – Bergi Jul 10 '22 at 20:21
  • Anyway defining user as function argument rewrites user variable – Kris1803 Jul 10 '22 at 20:25