【发布时间】:2021-01-29 04:10:06
【问题描述】:
我有多个传入的套接字数据处理程序。 它们都共享相同的初始验证检查和将缓冲区转换为数组的函数。此外,每次我需要遍历该数组的元素并执行特定的计算。但是,复制粘贴验证和数组生成代码看起来很奇怪。
// First handler
socket.on('data', (data) => {
const tags = getTags(data);
if (Array.isArray(tags)) {
tags.forEach((tag) => { // Everything is the same until this point
// Some computation
});
}
});
// ...
// Some other code
// ...
// Another handler
socket.on('data', (data) => {
const tags = getTags(data);
if (Array.isArray(tags)) {
tags.forEach((tag) => { // Again the same code is duplicated up to this point
// Some different computation here
});
}
});
我如何概括这种基于循环的验证和数组生成,并从中制作一个抽象且可重用的函数,这样我就不必复制和粘贴?
【问题讨论】:
标签: javascript node.js sockets