You are reading a single comment by @JumJum and its replies. Click here to read the full conversation.
  • Promises are a powerful tool to avoid callback-hell.
    For Espruino I was searching for a tiny solution and found 7 Lines from Krasimir.
    Based on this I wrote a simple flow solution.

    var async = function(funcs,scope,done ) {
      var _seq = 0,stopped = false;
      this.scope = scope;
      this.next = function(){this.goto(_seq,arguments);};
      this.goto = function(seq,args){
        if(seq < funcs.length){
          if(!stopped){ funcs[seq](args);_seq = seq + 1;} }
        else{done(args);}
      };
      this.exit = function(){stopped = true;done(arguments);};
      this.next();
    };
    

    It supports

    1. step by step using next()
    2. jumping from function to function using goto(funcNr)
    3. option to exit in each function using exit()
    4. local data using scope-object
    5. data handover from function to function, see async2, async3

    Handling is simple as you can see here:

    function logger(seq,value){ console.log(seq,new Date(),value); }
    
    function async1(){
      async([
          function(){setTimeout(function(){logger(­"1.0",scope);next();},1000);},
          function(){setTimeout(function(){logger(­"1.1",scope);next();},1000);}
        ],
        { title:"async1",value: 1},
        function(){logger("1 done",scope);async2();}
      );
    }
    function async2(){
      async([
          function(){
            scope.n_val = 22;
            setTimeout(function(){logger("2.0",scope­);next();},1000);
          },
          function(){setTimeout(function(){logger(­"2.1",scope);next();},1000);}    
        ],
        { title:"async2",value: 2},
        function(){logger("2 done",scope);async3();}
      );
    }
    function async3(){
      async([
          function(){setTimeout(function(){logger(­"3.0",scope);next(33);},1000);},
          function(x){
            scope.n_val = x[0];
            setTimeout(function(){logger("3.1",scope­);next();},1000);
          }
        ],
        { title:"async3",value: 3},
        function(){logger("3 done",scope);async4();}
      );
    }
    function async4(){
      async([
          function(){setTimeout(function(){logger(­"4.0",scope);goto(2);},1000);},
          function(){setTimeout(function(){logger(­"4.1",scope);exit();},1000);},
          function(){setTimeout(function(){logger(­"4.2",scope);goto(1);},1000);},
        ],
        { title:"async4",value: 4},
        function(){logger("4 done",scope);}
      );
    }
    logger(0,obj);
    async1();
    
About

Avatar for JumJum @JumJum started