gpt4 book ai didi

node.js - 我应该为事件使用回调吗?

转载 作者:搜寻专家 更新时间:2023-11-01 00:35:11 25 4
gpt4 key购买 nike

在浏览 express 的一些旧文档时,我发现了这个使用“关闭”事件回调的示例:

app.get('/page/', function (req, res) {
res.writeHead(200, { /* . . . */ );
res.write('\n');
req.on("close", function () {
// do something when the connection is closed
});
});

这在 ES10 中被认为是好的做法吗?我应该这样写代码,还是需要考虑其他事件方法?

最佳答案

这仍然是标准做法。如您所见,此示例取自 4.x (latest) Express.js docs

app.get('/', function (req, res) {
res.send('GET request to homepage');
});

如果你愿意,你可以做的一件事就是使用arrow function notation定义你的回调。像这样

app.get('/page/', (req, res) => {
res.writeHead(200, { /* . . . */ });
res.write('\n');
req.on("close", () => {
// do something when the connection is closed
});
});

关于node.js - 我应该为事件使用回调吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54592046/

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