在Node.js中构造事件监听器

时间:2019-03-25 15:53:48

标签: javascript node.js

我正在使用许多API,这些API的适配器包括许多事件侦听器,我寻求有关如何改进代码结构的建议,尤其是在将代码从app.js移至另一个目标(文件)方面。你们有如何做的秘诀吗?

代码示例(app.js):

import express from 'express';

// Dot Environment
const dotenv = require('dotenv');

// See if we can fetch the config
const result = dotenv.config()

// Ensure early that we can load the environment variables
if (result.error) throw result.error

// Example APIs
const { Api1 } = require('api1');
const { Api2 } = require('api2');
const { Api3 } = require('api2');

// Slack Adapter
const api1Events = Api1('x');
const api2Events = Api2('z');
const api3Events = Api3('y');

const request = require('request');

// Express
const app = express();

// Middleware
app.use('/api1/events', api1Events.expressMiddleware());
app.use('/api2/events', api2Events.expressMiddleware());
app.use('/api3/events', api3Events.expressMiddleware());

// Event listeners
api1Events.on('something', (data) => func1(data));
api2Events.on('something', (data) => func2(data));
api3Events.on('something', (data) => func3(data));

function func1(data) {
  // Image 1000 lines below calling tons of other functions
}

function func2(data) {
  // Image 1000 lines below calling tons of other functions
}

function func3(data) {
  // Image 1000 lines below calling tons of other functions
}

// Listener
app.listen(3000, () => console.log('Example app listening on port 3000!'));

0 个答案:

没有答案