【发布时间】:2015-08-04 12:06:20
【问题描述】:
我刚开始用 node.js 编码,我知道 node.js 是异步的,但不知道如何处理这个问题。 我正在查询 postgresql 并按如下方式构建 JSON,
我添加了我的代码:
var express = require('express');
var router = express.Router();
var pg = require('pg');
var client = require('../routes/database.js');
var cookieParser = require('cookie-parser');
var dateFormat = require('date-format');
var async = require('async');
var today = dateFormat(new Date());
router.post('/conversation/my', function(req, res) {
var userId = 59;
var limit = 10;
var offset = 0;
var postgresql = "select id from conversation where party_id = '" + userId + "' and reply_id = 0 order by created_on desc limit " + limit + " offset " + offset + "";
var postsJSON = { };
var arr = new Array();
client.query(postgresql, function(err, data) {
if (err) {
console.log(err);
return rollback(client);
}
var rows = data.rows;
for ( i = 0; i < rows.length; i++) {
var post = rows[i];
var post_obj = {};
post_obj.id = post.id;
getConversationResponse(post.id, function(err, res) {
if (!err) {
post_obj.actor = res;
arr.push(post_obj);
console.log(JSON.stringify(arr));
res.send({
data : arr
});
}
});
}
});
});
function getConversationResponse(conversation_id, cb) {
client.query('SELECT * FROM people WHERE id ='+conversation_id+';', function(err, actor) {
client.query('SELECT * FROM users WHERE id ='+conversation_id+';', function(err, user) {
var actor_obj = {};
actor_obj.id = user.id;
actor_obj.name = user.name;
actor_obj.email = user.email;
client.end();
cb (null,actor_obj);
});
});
}
module.exports = router;
但我收到错误:
{ [Error: write EPIPE] code: 'EPIPE', errno: 'EPIPE', syscall: 'write' }
events.js:72
throw er; // Unhandled 'error' event
^
Error: write EPIPE
at errnoException (net.js:901:11)
at Object.afterWrite (net.js:718:19)
npm ERR! weird error 8
npm WARN This failure might be due to the use of legacy binary "node"
npm WARN For further explanations, please read
/usr/share/doc/nodejs/README.Debian
【问题讨论】:
-
您在尝试从对话中获取数据时是否收到此错误?还是其他两张桌子?
-
其他两个表。抱歉,我错过了 3 行代码。
-
res.send({ data : arr });
标签: json node.js postgresql