【发布时间】:2016-01-31 19:02:15
【问题描述】:
我有一个使用await 调用的异步函数,我认为当你使用await 时,它应该暂停函数执行,直到它收到它的值。出于某种原因,它对我不起作用。
这是我的函数(它在一个类中):
async userExistsInDB(email) {
let userExists;
await MongoClient.connect('mongodb://127.0.0.1:27017/notificator', async(err, db) => {
if (err) throw err;
let collection = db.collection('users');
userExists = await collection.find({email: email}).limit(1).count() > 0;
console.log("INSIDE:\n", userExists);
db.close();
});
console.log("OUTSIDE:\n", userExists);
return userExists;
}
这是我在同一个类中的另一个函数中调用它的方式:
async getValidationErrors(formData) {
let userExists = await this.userExistsInDB(formData.email);
console.log("ANOTHER FUNC:\n", userExists);
}
所以,我得到以下输出:
OUTSIDE:
undefined
ANOTHER FUNC:
undefined
INSIDE:
true
虽然值 INSIDE: true 我希望第一个打印出来。
基本上,我需要的是从userExistsInDB 函数中获取布尔值userExists 并在其他代码中使用它。
我在这里做错了什么?
【问题讨论】:
标签: ecmascript-6 async-await ecmascript-2017