【问题标题】:sync functions node.js with postgresql?将功能 node.js 与 postgresql 同步?
【发布时间】:2016-07-18 17:42:43
【问题描述】:

我在管理异步函数时遇到了一些问题。这是我的代码:

    var query = client.query("select * from usuario");

    query.on('row', function(user) {
    var queryInterest = client.query("select interes.nombre from interes inner join relacioniu on relacioniu.idinteres=interes.id where relacioniu.idusuario = '"+user.id+"'");
    queryInterest.on('row',function(row) {
            user.interest = row;
            console.log("user added");
        });
    users.push(user);
    });
// After all data is returned, close connection and return results
    query.on('end', function() {
        done();
        console.log("finish");
        return res.json(users);
    });

users数组在queryInterest执行之前推送一个用户,所以永远不会添加用户的兴趣。我该如何解决这个问题?

非常感谢

【问题讨论】:

  • 为什么不能将users.push(user); 移动到queryInterest.on 中。这将解决您的问题。
  • 在这种情况下返回的代码是一个空数组
  • 是的,因为您的结束事件在 query 对象上。因此,一旦查询完成,它就会返回对象。你可以考虑使用async库。
  • 查看pg-promise,它更容易使用;)

标签: javascript node.js postgresql express asynchronous


【解决方案1】:
var query = client.query("select * from usuario");

query.on('row', function(user) {
var queryInterest = client.query("select interes.nombre from interes inner join relacioniu on relacioniu.idinteres=interes.id where relacioniu.idusuario = '"+user.id+"'");
queryInterest.on('row',function(row) {
        user.interest = row;
        users.push(user); // Moved it here; this is async, too.
    });
});

【讨论】:

  • 您修改的退出是:Starting child process with 'node ./bin/www' finish GET /api/v1/tander 200 28.330 ms - 2 user added user added 所以返回代码现在是空的
猜你喜欢
  • 1970-01-01
  • 2016-02-11
  • 2015-02-23
  • 2017-06-20
  • 2020-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多