【问题标题】:Return list from Graphql resolve从 Graphql 解析返回列表
【发布时间】:2018-02-13 00:26:16
【问题描述】:
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;
  }*/
},

我有一个 graphql 解析,我在 findById 回调中获取了 User 对象。该特定对象调用getFriends,它是猫鼬插件(朋友之友)的一部分,并且getFriends回调中的console.log包含终端中的列表,所以我知道getFriends 正在返回正确的数据,但我不知道如何将值返回到我的 React-Native 组件中。在过去的 8 小时里,我已经尝试了所有我能想到的东西,但无法从这个函数中得到返回的值。

【问题讨论】:

  • 你尝试过使用 state 吗?

标签: react-native mongoose callback graphql graphql-js


【解决方案1】:

您已经很接近了,但是在使用解析器时需要记住以下几点:

  • 您的解析器必须返回任一与架构中指定的类型/标量匹配的值将解析为该值的 Promise。 p>

  • Mongoose 操作 can return a promises,你应该利用它们的这个特性,而不是试图将回调包装在 Promise 中,因为这很容易变得混乱

  • 至少在这种情况下,回调中的返回语句)实际上并没有做任何事情。另一方面,then 中的 return 语句决定了 Promise 将解析的内容(或链中下一个要调用的 Promise)。

我想你的解析器需要看起来像这样:

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)
        })
      })
    })
}

【讨论】:

    猜你喜欢
    • 2019-07-25
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 2017-04-28
    • 2013-03-22
    • 2018-11-28
    相关资源
    最近更新 更多