我正在处理一小段使用express的nodeJS代码。该应用程序将有效载荷作为POST
接收,并将其发送到另一种方法,该方法将其提交给kafka
。一旦发生这种情况,我需要返回一个响应来表示,以便它可以根据状态关闭连接(例如,返回200响应)。
// producer.js
// Defined variables
var kafka = require('kafka-node'),
Producer = kafka.Producer;
module.exports = {
sendToProducer: function (payload) {
// Define our kafka settings
var client = new kafka.KafkaClient(),
producer = new Producer(client);
// On producer ready
producer.on('ready', function () {
// Send our payload to our topic
producer.send(payload, function (err, data) {
console.log(data);
// Return our response back to `app.js` so express can handle it.
});
});
// On producer error
producer.on('error', function (err) {
console.log('Producer Error', err)
})
}
};
// app.js
app.post('/payload', function (req, res) {
// Define our route
const payload = req.body;
const route = payload.route;
// Check to see if we have a route
if(!route){
logError('no route');
}
let mappedData = [{ topic: 'test', messages: 'hi... ', partition: 0 }]
// Based on the route
switch(route){
// Receive data
case 'ingest':
producer.sendToProducer(mappedData);
// How can I tell express the status of the above method so that we can close the request? (ex 200 response for example?)
break;
// Handle undefined routes
default:
break;
}
});
在我的app.js
案例陈述中,如何等待producer.sendToProducer(mappedData);
的响应/回叫,以便我可以适当地处理快递状态?
答案 0 :(得分:1)
确保您的sendToProducer()
是promise
/ async
函数:
app.post('/payload', async function (req, res) {
// Define our route
const payload = req.body;
const route = payload.route;
// Check to see if we have a route
if(!route){
logError('no route');
}
let mappedData = [{ topic: 'test', messages: 'hi... ', partition: 0 }]
// Based on the route
switch(route){
// Receive data
case 'ingest':
await producer.sendToProducer(mappedData);
// How can I tell express the status of the above method so that we can close the request? (ex 200 response for example?)
break;
// Handle undefined routes
default:
break;
}
});