class Example {
constructor(id) {
this.id = this.getId();
}
getId() {
inquirer
.prompt({
message: "Enter id?",
type: "input",
name: "employeesId",
})
.then((answer) => (this.id = answer.employeesId));
}
}
const testExample = new Example();
testExample.getId()
console.log(testExample.id); // <-- expected to log the id after user has entered it, instead returns undefined
So I'm new to OOP and just would like to understand why this won't work, any help would be appreciated.
A work around with explanation would also be highly appreciated.
Thanks in advance.
It takes a while for the
then()
callback to get called. But when you do this:You aren't waiting for the
inquirer
to finish and set theid
. There's no way to wait for it right now becausegetId()
is avoid
method. It needs to return aPromise
.The best way to do this is with
async
/await
syntax. If you makegetId()
anasync
method then that means it will return aPromise
that you canawait
.It is not possible to definitely set the id to a
number
in the constructor because the constructor cannot be asynchronous. You can either havethis.id
be aPromise
which resolves to anumber
or you can have it start out asundefined
and then get set to a number once theinquirer
is finished.It looks like you are currently accepting an
id
as an argument to the constructor but you don't use it, so I'm not sure what's going on there.With
this.id
as maybeundefined
:With
this.id
as aPromise
: