2017-03-07 9 views
1

그래서 컨트롤러에서 일부 코드를 줄이기 위해 여러 도우미를 작성하고 있습니다. 그래서 Lookup이라는 클래스를 만들어 데이터베이스에서 사용자를 검색 할 수있게 도와 주었고 searchAccountKey (key, callback)를 만들었습니다. 그래서,이 메서드를 사용할 때마다 사용자 개체가 사용자 대신 아무것도 반환하지 않는 것처럼 보입니다.Lookup 클래스 메서드가 사용자 데이터 대신 빈 객체를 반환합니다.

나는이 현상이 수율로 인해 발생하고 있다고 생각하지만 수율을 사용하면 오류가 발생합니다.

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을 사용한다면이 종류의 비동기 제어 흐름에 콜백 대신 약속을 사용해야합니다. – 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) 
    // ... 
} 

이 변경 후에는 yieldLookup.searchAccountKey를 호출해야합니다.

yield Lookup.searchAccountKey(...)