2017-03-07 64 views
1

所以,我创建不同的帮助器来减少我的控制器上的一些代码。所以我创建了一个名为Lookup的类来帮助我搜索数据库中的用户,并创建了一个searchAccountKey(key,callback)。所以,每当我使用这个方法时,它似乎能够工作,但是用户对象返回时没有任何东西而不是用户。查找类方法返回空对象而不是用户数据

我怀疑这是由于收益率,但当我使用yield时,它给了我一个错误。

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(线44)

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

编辑:每当我把得到User.findBy()

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

代码的盈:

'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

如果你真的使用ES6,你应该使用Promises而不是回调来实现这种异步控制流程。 – gyre

+0

我对Promises不熟悉。你能联系我一些关于这方面的很好的文档吗? – Ethan

+0

https://www.promisejs.org/ – gyre

回答

2

关键字yield只能在发生器内部使用。 searchAccountKey是目前正常的功能。您需要在函数的名称前使用*使其成为generator

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

这种变化之后,你就需要调用Lookup.searchAccountKeyyield也。

yield Lookup.searchAccountKey(...) 
相关问题