gpt4 book ai didi

javascript - 退出一系列嵌套回调

转载 作者:行者123 更新时间:2023-12-02 15:32:11 24 4
gpt4 key购买 nike

在下面的代码中,当从 deleteUser 的回调函数返回 err 变量时,我想将错误插入数据库并结束 HTTP 请求(并且这个整个代码块),并return res.send(500)

相反,即使 HTTP 请求已经结束,代码也会继续运行并调用 db.destroy。帖子底部的日志证明了这一点。

// 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 函数。

Node 中是否有解决此问题的通用设计模式?

我是否应该在 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: 'testuser@xyz.com',
Status: 0,
Notes: 'POST 500 has returned an error.' }

最佳答案

首先,yes,在关闭 if() {} 之前添加一个 return 语句。这很关键。

其次,您的代码遭受 callback hell 的影响,并且您应该认真考虑切换到更“现代”的替代方案,我个人最喜欢的是 promise 。 Here's a great article about this .

对于 Node ,请尝试查看 bluebirdes6-promisify

关于javascript - 退出一系列嵌套回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33222152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com