Den*_*nko 1 async-await ecmascript-6 ecmascript-2017
我有使用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;
}
Run Code Online (Sandbox Code Playgroud)
这是我在同一类中的另一个函数中调用它的方式:
async getValidationErrors(formData) {
let userExists = await this.userExistsInDB(formData.email);
console.log("ANOTHER FUNC:\n", userExists);
}
Run Code Online (Sandbox Code Playgroud)
因此,我得到以下输出:
OUTSIDE:
undefined
ANOTHER FUNC:
undefined
INSIDE:
true
Run Code Online (Sandbox Code Playgroud)
虽然INSIDE: true我希望第一个打印出来的值。
基本上,我需要userExists从userExistsInDB函数中获取布尔值并在其他代码中使用它。
我在这里做错了什么?
await仅与promise一起使用,因此MongoClient.connect(…)需要返回promise。但是,您将其用作回调API,甚至将其用作async(返回承诺)回调函数也无法使用。假设mongo在不传递回调的情况下返回promises,则代码应类似于
async function userExistsInDB(email) {
let db = await MongoClient.connect('mongodb://127.0.0.1:27017/notificator');
let collection = db.collection('users');
let userExists = (await collection.find({email: email}).limit(1).count()) > 0;
db.close();
return userExists;
}
Run Code Online (Sandbox Code Playgroud)
虽然理想情况下您宁愿这样做
async function userExistsInDB(email) {
let db = await MongoClient.connect('mongodb://127.0.0.1:27017/notificator');
try {
let collection = db.collection('users');
let userCount = (await collection.find({email: email}).limit(1).count();
return userCount > 0;
} finally {
db.close();
}
}
Run Code Online (Sandbox Code Playgroud)