如何使用grpc返回用户列表,结果为空:
我是http://condorjs.com,用于创建grpc服务器
class User {
getUser(ctx) {
models.users.findAll({
where: { userId: ctx.req.userId }
}).then(function(users){
// return a list of users
for (var i = 0, len = users.length; i < len; i++) {
result.push({'userId': users[i].userId, 'userName': users[i].userName);
}
return { 'users': result};
});
}
}
const options = {
'listen': '0.0.0.0:50051',
'rootProtoPath': 'protos',
};
const app = new Condor(options)
.add('user.proto', 'User', new User())
.start();
GRPC客户电话:
var PROTO_PATH = __dirname + '/../proto/profile.proto';
var grpc = require('grpc');
var user_proto = grpc.load(PROTO_PATH).user;
function main() {
var client = new guser_proto.User('localhost:50051',
grpc.credentials.createInsecure());
client.getUser({userId: '8888'}, function(err, response) {
console.log(response);
});
}
main();
原型:
message UserResponse {
message User{
string userId = 1;
string userName = 2;
}
repeated User users= 1;
}
答案 0 :(得分:1)
你还没有在函数定义中收到任何回调方法,所以我添加了一个回调参数,这个回调方法将使用必需的参数调用。您将通过主方法
接收数据 getUser(ctx, callback) {
models.users.findAll({
where: { userId: ctx.req.userId }
}).then(function(users){
// return a list of users
for (var i = 0, len = users.length; i < len; i++) {
result.push({'userId': users[i].userId, 'userName': users[i].userName);
}
callback(null,{ 'users': result});
}.bind(this));
}
}
这肯定会在这里返回您的数据
function main() {
var client = new guser_proto.User('localhost:50051',
grpc.credentials.createInsecure());
client.getUser({userId: '8888'}, function(err, response) {
console.log(response); // it will print here
});
}