合并node.js模块导出中的多个回调

时间:2016-07-12 06:07:49

标签: node.js callback sails.js

我有一个sails.js服务,它使用restler(rest-client)对外部api进行api调用并获取数据。

该模块如下所示:

var rest = require('restler');

module.exports = {
    config: {
        url: sails.config.remote_api.base_url.concat('/countries'),
        rejectUnauthorized: sails.config.remote_api.validateSsl,
        options: { 'Content-Type': 'application/json' }
    },
    find: function(headers, payload, callback) {
        var request = rest.get(this.config.url, this.config.options);
        sails.log.info('Outgoing Request', { log_id: headers[x - request - id], method: request.method, host: request.host, url: request.url });

        request.on('2XX', function(data, response) {
            callback(data, response);
        });
    }
}

在上面的代码中, request.on('2XX',...)处理响应代码在200系列中时发出的事件。

当我们为响应代码在300,400,500系列中发出的事件添加其他处理程序时...这会为每个块创建相同回调函数的重复。对于例如

var rest = require('restler');
module.exports = {
    config: {
        url: sails.config.remote_api.base_url.concat('/countries'),
        rejectUnauthorized: sails.config.remote_api.validateSsl,
        options: { 'Content-Type': 'application/json' }
    },
    find: function(headers, payload, callback) {
        var request = rest.get(this.config.url, this.config.options);
        sails.log.info('Outgoing Request', { log_id: headers[x - request - id], method: request.method, host: request.host, url: request.url });

        request.on('2XX', function(data, response) {
            callback(data, response);
        });

        request.on('3XX', function(data, response) {
            callback(data, response);
        });

        request.on('4XX', function(data, response) {
            callback(data, response);
        });

        request.on('5XX', function(data, response) {
            data = {};
            data.succeeded = false;
            data.failureCode = 'SYSTEM ERROR';
            data.failureReason = 'A system error has occurred. Please try again. If the problem persists contact support';
            callback(data, response);
        });

        request.on('error', function(data, response) {
            data.succeeded = false;
            data.failureCode = 'SERVICE UNAVAILABLE';
            data.failureReason = 'The service is temporarily unavailable. Please try again later.';
            callback(data, response);
        });
    }
}

我们如何避免重复以下行?

function(data, response) {
    callback(data, response);
}

1 个答案:

答案 0 :(得分:1)

不,你真的不应该。您基本上已经处理了不同的事件,例如2XX3XX等。每个事件都是单独处理的,这是一个很好的做法。再简化可能会破坏整洁的设计。

虽然您可以直接使用callback代替

function(data, response) {
    callback(data, response);
}
像这样

request.on('2XX', callback);