在以下代碼中,當從回調函數deleteUser
返回一個err
變量時,我想將錯誤插入到數據庫中並使用return res.send(500)
結束HTTP請求(以及整個代碼塊)。退出一系列嵌套回調函數
取而代之的是,代碼繼續運行,調用db.destroy
,即使HTTP請求已經結束。這由帖子底部的日誌證明。
// DELETE
app.del('/api/users', function(req, res) {
var id = req.query.id;
// get latest copy of database entry first, in case we need to save error message
db.get(id, {revs_info: true}, function(err, doc) {
if (err) {
console.error('Unable to find document', id, 'due to:', err);
return res.send(500);
} else {
// issue delete request first, if fails save error message
deleteUser(doc.EmailAddress, function(err) {
if (err) {
// update database with error message (if there's already a message, append)
doc.Notes = (doc.Notes === '') ? err : err + " " + doc.Notes;
db.insert(doc, function(err, document) {
if(err) {
console.error('Deleting a user failed (1) and updating database with error status failed (2) as well. 1:', doc.Notes, '2:', err);
return res.send(500);
} else {
console.error('Deleting a user failed (with the following) and the error has been stored in the database:', doc.Notes);
return res.send(500);
}
});
}
// proceed to delete from database as well
db.destroy(doc._id, doc._rev, function (err, body) {
if(err) {
console.error('Error deleting document', doc._id, 'with:', err);
return res.send(500);
} else {
if (doc._revs_info) delete doc._revs_info;
console.log('Succesfully deleted user from system and our database:', doc);
return res.send(200);
}
});
});
}
});
});
我認爲這種情況正在發生,因爲我return
語句只結束db.insert
功能。
在節點中有解決這個問題的常見設計模式嗎?
我應該簡單地在db.insert
聲明之後但在結束if (err) {
代碼塊之前添加另一個return
聲明嗎?發出DELETE請求到我的服務器實例後
日誌:
Deleting a user failed (with the following) and the error has been stored in the database: POST 500 has returned an error.
127.0.0.1 - - [Mon, 19 Oct 2015 02:50:19 GMT] "DELETE /api/users?id=11 HTTP/1.1" 500 21 "http://localhost:3000/" "Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0"
Succesfully deleted user from system and our database: { _id: '11',
_rev: '3-e6fec584448d664476ddaf3b7e150cd7',
EmailAddress: '[email protected]',
Status: 0,
Notes: 'POST 500 has returned an error.' }