12

我正在尝试检查email集合中是否存在提供的用户users,但我的函数每次调用都会返回 undefined 。我使用 es6 并且async/await为了摆脱很多回调。这是我的函数(它在一个类中):

async userExistsInDB(email) {
    let userExists;
    await MongoClient.connect('mongodb://127.0.0.1:27017/notificator', (err, db) => {
        if (err) throw err;

        let collection = db.collection('users');

        userExists = collection.find({email: email}).count() > 0;
        console.log(userExists);

        db.close();
    });
    console.log(userExists);
    return userExists;
}

所以,调用中的第一个console.log总是.connect返回false,因为返回的值.find不是一个数组,它是一个看起来像这样的巨大对象:

{ connection: null,
  server: null,
  disconnectHandler: 
   { s: { storedOps: [], storeOptions: [Object], topology: [Object] },
     length: [Getter] },
  bson: {},
  ns: 'notificator.users',
  cmd: 
   { find: 'notificator.users',
     limit: 0,
     skip: 0,
     query: { email: 'email@example.com' },
     slaveOk: true,
     readPreference: { preference: 'primary', tags: undefined, options: undefined } },
  options: 
........
........

最后一个console.log总是未定义的(虽然我认为不应该那样,因为await等待异步调用结束,对吧?)


我只需要我的函数返回一个布尔值,而不是一个Promise或什么。

有人可以帮我吗?

更新 1

console.log(collection.findOne({email: email}));里面.connect返回这个:

 { 'Symbol(record)_3.ugi5lye6fvq5b3xr': 
   { p: [Circular],
     c: [],
     a: undefined,
     s: 0,
     d: false,
     v: undefined,
     h: false,
     n: false } }

更新 2

似乎这是我对 es7 了解不足的问题async/await

现在里面的代码.connect返回所需的值。

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;

        db.close();
    });
    console.log(userExists); // <--- this is not called at all
    return userExists;
}

但是,现在根本不执行呼叫console.log之后的或任何事情。.connect

现在,每次我在userExistsInDB()某处调用该函数console.log及其结果时,都会得到以下信息:

 { 'Symbol(record)_3.78lmjnx8e3766r': 
   { p: [Circular],
     c: [],
     a: undefined,
     s: 0,
     d: false,
     v: undefined,
     h: false,
     n: false } }

任何想法为什么会这样?

4

1 回答 1

13

好的,这就是我的工作方式:

async function userExistsInDB(email, password) {
    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,
                password: password
            }).limit(1).count());
        return userCount > 0;
    } finally {
        db.close();
    }
}

并且因为async函数声明中的关键字保证返回值将是 a Promise,所以从这个函数中获取真正返回结果的唯一方法是:

let result = await this.userExistsInDB(email, password);在另一个声明的函数内async

于 2015-11-02T07:37:40.410 回答