Callback hell in nodejs?

前端 未结 3 1535
执笔经年
执笔经年 2020-11-30 05:29

In below code am I in callbackhell? How to overcome such scenario without using any async modules in pure javascript?

emailCallBack(e_data, email);
if (email         


        
3条回答
  •  情深已故
    2020-11-30 05:57

    I've put another solution in my blog. It is ugly but it is the most readable thing I could do with pure javascript.

    var flow1 = new Flow1(
        {
            execute_next_step: function(err) {
                if (err) {
                    console.log(err);
                };
            }
        }
    );
    
    flow1.execute_next_step();
    
    function Flow1(parent_flow) {
        this.execute_next_step = function(err) {
            if (err) return parent_flow.execute_next_step(err);
            if (!this.next_step) this.next_step = 'START';
            console.log('Flow1:', this.next_step);
            switch (this.next_step) {
                case 'START':
                    this.next_step = 'FIRST_ASYNC_TASK_FINISHED';
                    firstAsyncTask(this.execute_next_step.bind(this));
                    break;
                case 'FIRST_ASYNC_TASK_FINISHED':
                    this.firstAsyncTaskReturn = arguments[1];
                    this.next_step = 'ANOTHER_FLOW_FINISHED';
                    this.another_flow = new AnotherFlow(this);
                    this.another_flow.execute_next_step();
                    break;
                case 'ANOTHER_FLOW_FINISHED':
                    this.another_flow_return = arguments[1];
                    this.next_step = 'FINISH';
                    this.execute_next_step();
                    break;
                case 'FINISH':
                    parent_flow.execute_next_step();
                    break;
            }
        }
    }
    
    function AnotherFlow(parent_flow) {
        this.execute_next_step = function(err) {
            if (err) return parent_flow.execute_next_step(err);
            if (!this.next_step) this.next_step = 'START';
            console.log('AnotherFlow:', this.next_step);
            switch (this.next_step) {
                case 'START':
                    console.log('I dont want to do anything!. Calling parent');
                    parent_flow.execute_next_step();
                    break;
            }
        }
    }
    

提交回复
热议问题