【问题标题】:How to use async/await pattern with gRPC Web?如何在 gRPC Web 中使用 async/await 模式?
【发布时间】:2020-12-17 11:21:36
【问题描述】:

我正在开发一个 Vue.js Web 应用程序,我正在使用 gRPC 来确保通信。

在前端,我使用的是网页版的 gRPC:grpc-web

一切正常;但是,当我在商店中进行 API 调用时,例如:

async fetchEcho() {
    const echoService = new EchoServiceClient('http://localhost:8080', null, null);

    const request = new EchoRequest();
    request.setMessage('Hello World!');

    const call = echoService.echo(request, {'custom-header-1': 'value1'},
      (err: grpcWeb.Error, response: EchoResponse) => {
        console.log(response.getMessage());
    });
}

在我的 Vue 文件中进行调用时如何使用async/await 模式,例如:

await fetchEcho();
// ...

并等待 API 调用完成以恢复我的程序进程?

谢谢!

【问题讨论】:

  • await 与承诺一起使用。是否有echo 的形式返回承诺而不是调用回调?

标签: typescript vue.js async-await grpc grpc-web


【解决方案1】:

我正在使用 ServicePromiseClient,示例如下:

const echoServiceClient = new EchoServicePromiseClient("http://localhost:8080", null, null);

然后我可以创建异步函数来获取这样的数据:

async function fetchEcho() {
    const echoReq = new EchoRequest();
    echoReq.setMessage("Hello world!");
    try {
        const response = await echoServiceClient.echo(echoReq, {});
        return response;
    } catch (error) {
        console.log(error);
        return null;
    }
}

【讨论】:

猜你喜欢
  • 2020-06-11
  • 2021-01-19
  • 1970-01-01
  • 2014-01-26
  • 1970-01-01
  • 2021-11-18
  • 2019-07-20
  • 2021-10-10
  • 2019-07-24
相关资源
最近更新 更多