【发布时间】:2020-06-25 14:23:38
【问题描述】:
试图改变.then,像这样:
User.prototype.login = () => {
return new Promise((resolve, reject) => {
this.cleanup();
usersCollection
.findOne({ username: this.data.username })
.then((attemptedUser) => {
if (attemptedUser && attemptedUser.password == this.data.password) {
resolve("logged in");
} else {
reject("invalid something");
}
})
.catch(() => {
reject("Please, try again later");
});
});
第一个效果很好,但是当我尝试将其更改为 async/await 时,如下所示:
User.prototype.login = () => {
return new Promise(async (resolve, reject) => {
this.cleanup();
try {
const attemptedUser = await usersCollection.findOne({ username: this.data.username });
if (attemptedUser && attemptedUser.password == this.data.password) {
resolve("logged in");
} else {
reject("invalid something");
}
} catch {
reject("Please, try again later");
}
});
};
它给我一个错误,this.cleanup() 不是一个函数,经过几次尝试,我意识到异步以某种方式改变了“this”。
你能帮帮我吗,我在哪里出错了?
【问题讨论】:
-
为什么要将 promise 和 async/await 放在一个地方?
-
我意识到 async 会以某种方式改变“this”。 async 与
this的值的设置方式无关 -
这与
async关键字的使用无关。如果此方法中的this应该是User对象,那么您可能会在几个地方出错。对于初学者,User.prototype.login不应该是箭头函数,因为它不会传递this中的实例值。它应该是一个常规的函数声明第二,你必须确保你正确地调用了someUserObj.login(),所以你必须向我们展示调用代码,让我们看看你是否正确地这样做了。
标签: javascript node.js