Skip to content

Using await in an async handler returns undefined to clients #22

@Ganitzsh

Description

@Ganitzsh

Hello,

I have an issue with empty response to clients when using await within async functions.

Here is my proto:

syntax = "proto3";

package user;

service User {
  rpc GetUserFullName(GetUserFullNameRequest) returns (GetUserFullNameResponse) {}
}

message GetUserFullNameRequest {
  string user_id = 1;
}

message GetUserFullNameResponse {
  string full_name = 1;
}

I have this handler:

import { UserModel } from 'mongoose/models';

async function getUserFullName(ctx) {
  const user = await UserModel.findById(ctx.req.userId);

  console.log(user); // The user is properly retrieved

   ctx.res = { fullName: `${user.firstName} ${user.lastName}` };
}

Very simple so far, but upon calling it with a client generated with grpc-caller I get this error:

const response = await userServiceClient.getUserFullName({
  userId: args.userId,
});
Error: 13 INTERNAL: Cannot read property 'fullName' of undefined
    at Object.callErrorFromStatus (/node_modules/@grpc/grpc-js/src/call.ts:81:24)
    at Object.onReceiveStatus (/node_modules/@grpc/grpc-js/src/client.ts:343:36)
    at Object.onReceiveStatus (/node_modules/@grpc/grpc-js/src/client-interceptors.ts:462:34)
    at Object.onReceiveStatus (//node_modules/@grpc/grpc-js/src/client-interceptors.ts:424:48)
    at /node_modules/@grpc/grpc-js/src/call-stream.ts:323:24
    at processTicksAndRejections (node:internal/process/task_queues:78:11) {
  code: 13,
  details: "Cannot read property 'fullName' of undefined",
  metadata: Metadata { internalRepr: Map(0) {}, options: {} }
}

But, when I change my hander to the following:

async function getUserFullName(ctx) {
  ctx.res = (async () => {
    const user = await UserModel.findById(ctx.req.userId);
    return { fullName: `${user.firstName} ${user.lastName}` };
  })()
}

It works fine, but I'm not sure why. Is it due to the UNARY nature of the call?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions