问题描述
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
所以我是 OOP 的新手,只是想了解为什么这不起作用,任何帮助将不胜感激。
也非常感谢提供解释的解决方法。
提前致谢。
解决方法
调用 then()
回调需要一段时间。但是当你这样做时:
testExample.getId()
console.log(testExample.id);
您不是在等待 inquirer
完成并设置 id
。现在没有办法等待它,因为 getId()
是一个 void
方法。它需要返回一个 Promise
。
最好的方法是使用 async
/await
语法。如果您将 getId()
设为 async
方法,则意味着它将返回一个 Promise
,您可以await
。
不可能在构造函数中明确地将 id 设置为 number
,因为构造函数不能是异步的。您可以让 this.id
成为解析为 Promise
的 number
,或者您可以让它以 undefined
开头,然后在 {{1 }} 完成。
看起来您目前正在接受 inquirer
作为构造函数的参数,但您没有使用它,所以我不确定那里发生了什么。
id
可能是 this.id
:
undefined
使用 class Example {
constructor() {
}
async getId() {
const answer = await inquirer
.prompt({
message: "Enter id?",type: "input",name: "employeesId",});
this.id = answer.employeesId;
}
}
const testExample = new Example();
await testExample.getId();
console.log(testExample.id);
作为 this.id
:
Promise