How do I avoid deeply nested code in node.js?

后端 未结 6 2175
执念已碎
执念已碎 2021-02-08 22:28

In node.js, it being event-driven, all I/O is done via callbacks. So I end up writing code that looks like this:

app.get(\'/test\', function (req, res) {
  ht         


        
6条回答
  •  醉话见心
    2021-02-08 23:21

    Another (and perhaps better) way to clean up this kind of thing is to use EventEmitters rather than callbacks. Here's an example showing several EventEmitters in use:

        var events = require('events'),
        util = require('util');
    
        var Search = function () {
        "use strict";
    
        var search,
            requestPageData,
            makeReturnObject,
            sendResults,
    
            emptyObj = {};
    
        events.EventEmitter.call(this);
    
        search = function (query) {
            this.emit("requestPageData", query);
        };
    
        requestPageData = function (query) {
            var resultsArray = [];
    
            // some logic
    
            if (.....some condition....) {
                this.emit("makeReturnObject", resultsArray);
            } else {
                this.emit("sendResults", emptyObj);
            }
        };
    
        makeReturnObject = function (resultsArray) {
            var resultsObj = {};
    
            if (magnetArray) {
    
                // some logic
    
                this.emit("sendResults", resultsObj);
            } else {
                this.emit("sendResults", emptyObj);
            }
        };
    
        sendResults = function (obj) {
            // finally, do whatever it is you want to do with obj
        };
    
        this.on("requestPageData", requestPageData);
    
        this.on("makeReturnObject", makeReturnObject);
    
        this.on("sendResults", sendResults);
    
        this.search = search;
    
    };
    
    util.inherits(Search, events.EventEmitter);
    module.exports = new Search();

提交回复
热议问题