Lookup class method returns empty object instead o

2019-08-01 03:30发布

问题:

So, I am creating different helpers to reduce some code on my controller. So I created a class called Lookup to help me search for users in my database and I created a searchAccountKey(key, callback). So, whenever I utilize this method it seems to work however the user object returns with nothing instead of the user.

I am suspecting this is happening because of yield but when I do use yield it gives me an error.

LookupHelper.js

'use strict';
const User = use('App/Model/User');
class LookupHelper {
  // Grab the user information by the account key
  static searchAccountKey(key, callback) {
      const user = User.findBy('key', key)
      if (!user) {
        return callback(null)
      }
      return callback(user);
  }

}

module.exports = LookupHelper;

UsersController (line 44)

Lookup.searchAccountKey(account.account, function(user) {
    return console.log(user);
});

EDIT: Whenever I put yield infront of the User.findBy()

The keyword 'yield' is reserved const user = yield User.findBy('key', key)

Code:

'use strict';
const User = use('App/Model/User');
class LookupHelper {
  // Grab the user information by the account key
  static searchAccountKey(key, callback) {
      const user = yield User.findBy('key', key)
      if (!user) {
        return callback(null)
      }
      return callback(user);
  }

}

module.exports = LookupHelper;

回答1:

The keyword yield can be only used inside a generator. searchAccountKey is currently a normal function. You need to use * before the name of the function to make it a generator.

static * searchAccountKey (key, callback) {
  const user = yield User.findBy('key', key)
  // ...
}

After this change you will need to call Lookup.searchAccountKey with yield also.

yield Lookup.searchAccountKey(...)