关于构造异步代码的建议

时间:2018-02-15 00:34:18

标签: javascript node.js

我目前正在为我的消息传递服务开发Node.js套接字服务器,并且一直在考虑重新组织我的代码以使其更易于理解,流程更好,最重要的是可管理的方法。为了了解我认为结构有什么问题,我将提出一个修剪版本:

'use strict';

let SocketServer = require('./InitializeServer.js'); // server initialization
const MessageSender = require('./Messaging.class.js'); // import the Messanger Class
const Database = require('./SQL.js');

const conn = Database.Connection;
const SQL = Database.SQL;

/** This method is in another file and establishes a secure websocket server
 *
 *  @param {ClientObject} An object that describes everything about the client
 *  @param {ConnectionObject} An object that describes everything about the currection connection of a user, note ConnectionObject depends on ClientObject
 *  @param {req} Connection request param
 */
SocketServer.runWebSocketServer(function (ClientObject, ConnectionObject, req) {
    let poll = null;
    let _self = ClientObject.get();

    const Messanger = new MessageSender(ClientObject);
    const Chat = new SocketServer.EventDispatcher(ClientObject, ConnectionObject, {
        // these events require a "verify" key
        verify: ['status', 'actions']
    });

    // all of my handlers go here

    Chat.on('message', function (data) {
        // send out messages
    }, true);

    Chat.on('status', function (data, subtype, applyToAll) {
        // send out status messages
    }, false);

    Chat.on('typing', function (data) { 
        // "is typing" mechanism
    }, true);

    Chat.on('actions', function (action, type) {
        // set actions
    }, true);

    Chat.on('loadMore', function (start) {
        // do something here
    }, true);

    Chat.on('close', function close() {
        console.log("CLOSE CONNECTION");
    });

    // do a few more general operations below
});

由于我是Node.js环境的新手,代码的重复部分会抛出一些标志。可扩展性通常受到这种重复行为的阻碍。作为一个考虑,我可以改变重复的行,以遵循更面向对象的方法*:

    Chat.on(new MessageEvent());
    Chat.on(new StatusEvent());
    Chat.on(new TypingEvent());
    Chat.on(new Actions());
    Chat.on(new LoadingEvent());
    Chat.on(new CloseEvent());

我不确定这是否是正确或最佳做法。你觉得怎么样?

*请注意,.on方法并非来自任何原生实施,因此我非常灵活

0 个答案:

没有答案