2017-03-07 18 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(...) 
相關問題