2017-09-04 4 views
0
fetchFriends: { 
    type: new GraphQLList(UserType), 
    args: { 
    currentId: { type: new GraphQLNonNull(GraphQLID) } 
    }, 
    resolve: (_, {currentId}) => { 
    return Promise.resolve() 
     .then(() => { 
     User.findById(currentId, (err, users) => { 
      users.getFriends((err, user) => { 
      console.log(user); 
      return user; 
      }); 
     }); 
     }) 

    } 
    /* another version what i tried that returns only the initial findById user 
    resolve: (_, {currentId}) => { 
    var value = User.findById(currentId, (err, user) => { 
     new Promise((resolve, reject) => { 
     user.getFriends((err, user) => { 
      console.log('fetch: ', user); 
      err ? reject(err) : resolve(user) 
     }); 
     }) 
    }) 
    return value; 
    }*/ 
}, 

나는 findById 콜백 내에서 사용자 개체를 얻고있다 graphql 해결했습니다. 그 특정 개체는 몽구스 플러그인 (friends-of-friends)의 일부인 getFriends를 호출하고 getFriends 콜백 내의 console.log는 터미널의 목록을 포함하므로 getFriends를 알 수 있습니다. 은 올바른 데이터를 반환하지만 어떻게 계산할 수 있습니까? 내 React-Native Component로 값을 반환합니다. 나는 지난 8 시간 동안 내가 생각할 수있는 모든 것을 시도해 왔고,이 함수에서 반환 된 값을 얻을 수 없다.반환 목록에서 Graphql 해결

+0

당신이 상태를 사용하여 시도 적이 있습니까? – bennygenel

답변

0

당신은 가까운,하지만 리졸버로 작업 할 때 명심해야 할 몇 가지가있다 :

  • 귀하의 리졸버에 지정된 유형/스칼라 일치 값 중 하나를 반환하는 당신 스키마 또는 a 해당 값으로 확인되는 약속.

  • 몽구스 작업 can return a promises, 당신은 실제로하지) 않고 쉽게이 상황에서 적어도 콜백 내부 혼란

  • 반환 문을 얻을 수있는이 같은 약속 내부 콜백을 래핑하는 것보다 그들 중이 기능을 활용한다 뭐든지해라. 반대로 then 안에있는 return 문은 약속이 해결할 내용 (또는 체인에서 다음에 호출 할 약속)을 ​​결정합니다.

나는 당신의 해결이 같은 볼 필요가 상상 :

resolve (_, {currentId}) => { 
    // calling exec() on the query turns it into a promise 
    return User.findById(currentId).exec() 
    // the value the promise resolves to is accessible in the "then" method 
    .then(user => { 
     // should make sure user is not null here, something like: 
     if (!user) return Promise.reject(new Error('no user found with that id')) 
     // we want the value returned by another async method, getFriends, so 
     // wrap that call in a promise, and return the promise 
     return new Promise((resolve, reject) => { 
     user.getFriends((error, friends) => { 
      if (error) reject(error) 
      resolve(friends) 
     }) 
     }) 
    }) 
}