How is, in the second last line, the object user
defined?
user
is the resolution value of the promise from client.logon
. It's set by the code in client.logon
that resolves the promise. When the promise is resolved (by that code in client.logon
), your then
handler is called and passed the resolution value as an argument (remember that user => ...
defines a function accepting a user
parameter; more in this question's answers). That's how you can see it, and how you can use its properties (which presumably were created by client.logon
).
For instance, client.logon
might look something like this (conceptually, not literally):
class Client {
// ...
logon() {
return new Promise((resolve, reject) => {
// start the login process, which is presumably asynchronous,
// and then in some handler for completion:
resolve(result); // Where `result` is the user object
});
}
// ...
}
It's the value logon
passes into resolve
that your then
handler receives.
Of course, logon
may not use new Promise
, it may well chain onto a promise from another function, but at some level, the innermost of those will create a promise via new Promise
(or async
, which is syntactic sugar for a function that creates and returns a promise).
Here's a simple live example:
class Client {
logon() {
return new Promise((resolve) => {
// Simulate asynchronous process via setTimeout
setTimeout(() => {
resolve({emailAddress: "foo@example.com"});
}, 100);
});
}
}
const client = new Client();
client.logon()
.then(user => console.log(user.emailAddress))
.catch(console.error);