【问题标题】:How to return a value from callback?如何从回调中返回值?
【发布时间】:2020-04-22 07:37:39
【问题描述】:

我正在尝试将 GraphQL (Apollo/Node.js) 和 gRPC (Go) 粘合在一起。到目前为止,我可以在他们之间进行交流。

但是,我无法从 gRPC 客户端回调中返回创建的用户值。

这是用户架构;

// schema.ts

import {gql} from 'apollo-server-express'

const schema = gql`
  type Mutation {
    addUser(input: AddUser): User
  }

  type User {
    id: ID!
    email: String
  }

  input AddUser {
    email: String!
    password: String!
  }
`

export default schema

这是解析器;

// resolver.ts

import {add} from '../client'

const resolver = {
  Query: {
    users: () => console.log('in progress'),
  },
  Mutation: {
    // addUser: (_: any, {input}: any) => add(input),

    // This successfully logs the `res`
    // addUser: (_: any, {input}: any) => add(input, (res: any) => console.log('Logged from resolver >', res)),

    // This returns null in mutation
    addUser: (_: any, {input}: any) => add(input, (res: any) => {
      return res
    }),
  }
}

export default resolver

这是 gRPC 客户端,它返回 undefined。

// client.ts

export async function add(input: any) {

  // Confirmed created in database
  client.addUser({
    email: input.email,
    password: input.password
  }, (_err: any, res: any) => {

    // Successfully logs `res`
    console.log('Logged res here > ', res)

    return res
  })
}

请帮帮我。


编辑:

我也试过回调函数:

export async function add(input: Input, callback: any) {
  try {
    await client.addUser({
      email: input.email,
      password: input.password
    }, (_err: any, res: any) => {
      console.log('Logged res here > ', res)
      return callback(res)
    })
  } catch (error) {
    console.log(error);
  }
}

在突变中仍然返回 null:

    addUser: (_: any, {input}: any) => add(input, (res: any) => {
      return res
    }),

【问题讨论】:

标签: node.js typescript graphql grpc apollo


【解决方案1】:

GraphQL 解析器应该返回一个适当类型的值,否则一个Promise 将解析为该值。 Callbacks 和 Promises 都是异步处理代码的方式,但是它们并不兼容。

目前尚不清楚您使用的是什么客户端库,但大多数使用回调的库现在也公开了一个 Promise API——如果您有,您应该使用它。如果这不是一个选项,您应该wrap the callback with a Promise。比如:

const resolver = {
  Mutation: {
    addUser: (_: any, {input}: any) => new Promise((resolve, reject) => {
      add(input, (res) => {
        resolve(res)
      })
    }),
  },
}

请注意,如果您的回调传递了错误,您应该确保调用 reject 时出现错误,而不是调用 resolve

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 2012-03-27
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    相关资源
    最近更新 更多