我正在向Nodejs服务器发送POST请求(使用Express)。在POST处理中,我需要从3个不同的文件中读取数据并将它们推送到3个数组中。但是,似乎res.end()在读取完成之前发生。 有人可以帮忙解决这个问题,这是我的过程功能。 (response = [[],[],[]])
app.post('/process_post', urlencodedParser, function(req, res) {
var readMail = readline.createInterface({
input : fs.createReadStream(path.join(process.cwd(), '/mail.txt'))
});
var readSubject1 = readline.createInterface({
input : fs.createReadStream(path.join(process.cwd(), '/subject1.txt'))
});
var readSubject2 = readline.createInterface({
input : fs.createReadStream(path.join(process.cwd(), '/subject2.txt'))
});
readMail.on('line', function(line) {
email.push(line);
});
readMail.on('close', function() {
// resolve(email);
console.log('finish mail');
});
readSubject1.on('line', function(line) { sub1.push(line) }).on('close', function() {
console.log('finish subject1');
});
readSubject2.on('line', function(line) { sub2.push(line) }).on('close', function() {
console.log('finish subject2');
});
var response = [email, sub1, sub2];
res.end(JSON.stringify(response));
});
答案 0 :(得分:0)
您必须使用异步进程。基本上,回调是许多nodejs方法的关键。我强烈建议你学习承诺,回调或像async这样的库。无论如何,我在您的代码中添加了promises。你应该在promise.all。
之后返回你的res.end函数var p1 = new Promise((resolve, reject) => {
readMail.on('line', function(line) {
email.push(line);
});
readMail.on('error', function(error) {
reject(error)
});
readMail.on('close', function() {
resolve(email);
});
});
var p2 = new Promise((resolve, reject) => {
readSubject1.on('line', function(line) {
sub1.push(line)
}).on('close', function() {
resolve(sub1);
}).on('error', function(err) {
reject(err);
})
});
var p3 = new Promise((resolve, reject) => {
readSubject2.on('line', function(line) {
sub2.push(line)
}).on('close', function() {
resolve(sub2);
}).on('error', function(err) {
reject(err);
})
});
Promise.all([p1, p2, p3])
.then(values => {
console.log('values [p1, p2, p3]');
res.end(values);
})
.catch(err => {
console.log(err);
})