如果db调用抛出一个错误,我该如何返回错误标题?

我有一个运行NodeJS和Couchbase的小型数据收集networking应用程序。 要求是当第三方向我们推送一些数据并且能够处理它时,我们返回200头,但是如果在存储这些数据时有任何问题,我们将返回500.这意味着,尝试使用失败的数据批次。

我遇到了一个总是返回200的问题(因为数据库调用是asynchronous完成的)。 这是一个例子:

... var app = express(); function create(req, res) { var error = false; // Parse all the entries in request for (var i = 0; i < req.body.length; i++) { var event = req.body[i]; if (!event.email) { // log error to file error = true; res.send("Event object does not have an email address!", 500); } // Greate the id index value var event_id = 'blah'; // See if record already exists db.get(event_id, function (err, result) { var doc = result.value; if (doc === undefined) { // Add a new record db.add(event_id, event, function (err, result) { if (err) { error = true; res.send('There were processing errors', 500); } }); } }); } if (error) res.send("Try again", 500); else res.send("OK", 200); } app.post('/create', create); 

有没有办法使应用程序等待这些数据库调用完成,即这个function是同步? 还是我用这个错误的技术? 🙁

我决定去NodeJS + Couchbase,因为我们可能会有非常高的调用数量,必须写入,读取和删除数据(小的JSON对象)。 编辑:啊数据结构可能会改变各种事件,所以能够存储非均匀形状的文件它的一个很大的优势!

这是async库的一个典型用例,它是一个带有许多模式的实用工具库,用于处理asynchronous函数。

由于您需要为每个logging调用一个asynchronous函数,因此可以使用async.each ,它为数组的所有元素执行asynchronous函数。 当所有asynchronous任务完成时,最后一个callback被调用。

 var app = express(); function handleEvent = function (event, callback) { if (! event.email) { callback(new Error('Event object does not have an email address!')); } var event_id = 'blah'; db.get(event_id, function (err, result) { var doc = result.value; if (doc === undefined) { // Add a new record db.add(event_id, event, function (err, result) { if (err) { callback(new Error('There were processing errors')); } else { callback(null); } }); } }); } function create(req, res) { // https://github.com/caolan/async#each async.each(req.body, handleEvent, function (err) { if (err) res.send(err.message, 500); else res.send('OK', 200); }); }