Node.js 如何将sequelizejs的结果列表返回给grpc?
如何使用grpc返回用户列表,结果为空: 我正在创建grpc服务器Node.js 如何将sequelizejs的结果列表返回给grpc?,node.js,sequelize.js,grpc,Node.js,Sequelize.js,Grpc,如何使用grpc返回用户列表,结果为空: 我正在创建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.len
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();
原型:
message UserResponse {
message User{
string userId = 1;
string userName = 2;
}
repeated User users= 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));
}
}
您是如何接收这些值的?第二,这个“用户”对象是否有任何数据?你能把它打印出来并检查一下吗?console.log给我结果:[{userId:'c46c4c9a0968450498f8de748d630c75'},{userId:'528ee92bbe9f4d3cbrc66fccf85cfb4c'},{userId:'3cd8004252454ae290e0569dec4ef7'}那么它工作了,对吗?唯一的问题是您没有很好地处理数据。此方法将被异步调用,因此您需要添加回调方法或其他方法来获取调用方法中的值。如果你告诉我这个代码的用法,我可以帮你。是的,我认为是异步问题,如果我只是返回数组,它就可以工作。更新了我的问题。我正在使用condor框架创建grpc服务器。
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
});
}