【问题标题】:gprc client async response NodeJSgprc 客户端异步响应 NodeJS
【发布时间】:2020-09-24 22:39:53
【问题描述】:

我正在尝试在函数中调用一个简单的 grpc 请求,但我不知道如何等待响应并将其传递到 grpc 调用之外。

应该是这样的:

Client: (parent, args, context, info) =>{
      client.Get({thing, objects, properties}, function(err, response) {
            //how to return the response outside?
          });
      //await for the response function.
};

是否可以在 client.Get 函数之外以某种方式返回响应? 有人有什么建议吗? 谢谢你的建议!

【问题讨论】:

    标签: node.js async-await graphql grpc rpc


    【解决方案1】:

    你有两种方法:

    1. 自己将 gRPC 的方法从 error first 回调封装到 promise。
    new Promise((resolve, reject) => client.Get({thing, objects, properties}, function(err, response) {
      if(err) {
        return reject(err)
      }
      resolve(response)        
    }))
    
    1. 使用grpc-promise来promisify gRPC客户端的方法。
    const grpc_promise = require('grpc-promise');;
    grpc_promise.promisifyAll(client);
    

    然后,您可以将这个 promisified gRPC 客户端传递给 GraphQL 上下文。 (根据函数签名猜你正在使用 GraphQL)。

    然后您可以在 GraphQL 解析器中返回一个承诺。

    Client: (parent, args, context, info) =>{
      return context.client.Get({thing, objects, properties})
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-29
      • 2017-08-27
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2015-07-06
      • 2016-06-25
      相关资源
      最近更新 更多