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的新手,我只是想知道为什么它不能工作,任何帮助都将不胜感激。
一个与解释周围的工作也将受到高度赞赏。
提前谢谢。
发布于 2021-06-05 04:53:47
调用then()回调需要一段时间。但是当你这样做的时候:
testExample.getId()
console.log(testExample.id);您不必等待inquirer完成并设置id。现在没有办法等待它,因为getId()是一个void方法。它需要返回一个Promise。
最好的方法是使用async/await语法。如果您将getId()设置为async方法,那么这意味着它将返回一个您可以await的Promise。
不可能在构造函数中明确地将id设置为number,因为构造函数不能是异步的。您可以让this.id成为一个解析为number的Promise,也可以让它从undefined开始,然后在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
class Example {
constructor() {
this.id = this.getId();
}
async getId() {
const answer = await inquirer
.prompt({
message: "Enter id?",
type: "input",
name: "employeesId",
});
return answer.employeesId;
}
}
const testExample = new Example();
const id = await testExample.id;
console.log(id);https://stackoverflow.com/questions/67343494
复制相似问题