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
inquirerto finish and set theid. There's no way to wait for it right now becausegetId()is avoidmethod. It needs to return aPromise.The best way to do this is with
async/awaitsyntax. If you makegetId()anasyncmethod then that means it will return aPromisethat you canawait.It is not possible to definitely set the id to a
numberin the constructor because the constructor cannot be asynchronous. You can either havethis.idbe aPromisewhich resolves to anumberor you can have it start out asundefinedand then get set to a number once theinquireris finished.It looks like you are currently accepting an
idas an argument to the constructor but you don't use it, so I'm not sure what's going on there.With
this.idas maybeundefined:With
this.idas aPromise: