庆祝可以出小区购物了,分享个原创js同步方案
js异步比较讨论,回调一层一层的有太麻烦。我们开发教学软件的,经常会有n个人说话,熟悉时序概念,所以这里做个step的同步方案。
直接上代码。
【index.html】
<!DOCTYPE html> <html <head> <meta charset="utf-8" /> <title>同步的一个想法</title> </head> <body> <script src="ZaShaoStep.js"></script> <script type="text/javascript"> var num=100; var $this='我是this';//模拟this var zss=new ZaShaoStep($this); /** @格式 var zss=new ZaShaoStep($this);//$this是传进入的值,通过zss.$this取出 zss.step('step1',()=>{});//定义步骤名称 出错后方便定位 zss.step(()=>{});//也可以省略名称,名称最后会自己识别成第n步,异常了自己数step排查 * */ zss.step('step1',()=> { console.log(zss.$this);//模拟this num++; console.log(1,num); zss.next(); }); zss.step('第2步',()=> { setTimeout(()=> { console.log(zss.$this);//模拟this num++; console.log(2,num); zss.next(); },1000); }); //省略步骤名称 zss.step(()=> { setTimeout(()=> { num++; console.log(3,num); zss.next(); },2000); }); zss.step(()=> { num++; console.log(4,num); zss.next(); }); zss.step(()=> { zss2.run(); }); zss.run(); //下面这个应该是不让用的 zss.step(()=> { setTimeout(()=> { num++; console.log(5,num); //zss.next(); },10); }); var zss2=new ZaShaoStep($this); zss2.step(()=> { num++; console.log('2-1',num); zss2.next(); }); zss2.step(()=> { setTimeout(()=> { num++; console.log('2-2',num); zss2.next(); },1000); }); zss2.step(()=> { setTimeout(()=> { num++; console.log('2-3',num); zss2.next(); },1000); }); </script> </body> </html>
【ZaShaoStep.js】
/** * 尝试寻找用一种简单的方法解决异步问题 * */ function ZaShaoStep(me) { var step_action=[]; var step_action_index=-1; var step_lock=false; var unique_id=0; var zashao_step= { $this:null, tag:'', run:function() { step_lock=true; this.next(); }, step:function() { //智能判断参数 var arg1=arguments[0]; var arg2=arguments[1]; if(typeof(arg1)=='function') { var action=arg1; var name=arg2; }else{ var action=arg2; var name=arg1; } if(step_lock) { console.error('step已上锁,step无法执行'); return false; } if(!name) { name=`第${step_action.length+1}个step`; } unique_id++; step_action.push({unique_id:unique_id,action:action,name:name}); }, next:function(){ step_action_index=step_action_index+1; if(step_action_index>=step_action.length) { //console.error(`step[${step_action[step_action_index-1].name}] 之后没有step; .next()执行已结束,自动忽略`); return false; } try{ step_action[step_action_index].action(); }catch(e){ console.error(`step[${step_action[step_action_index].name}] 执行异常`); } }, new:function(me){ this.$this=me; this.tag=(new Date()).valueOf()+'_'+Math.random(); console.log(this); return this; } } var result=zashao_step.new(me); return result; };
【用法】
var zss=new ZaShaoStep($this);//$this是传进this的值,通过zss.$this取出,改造代码的时候方便一点 zss.step('step1',()=>{});//定义步骤名称 出错后方便定位 zss.step(()=>{});//也可以省略名称,名称最后会自己识别成第n步,异常了自己数step排查 zss.run();//这个是开始执行,一般放最后 另每个step里需要zss.next();这样才能顺接下一步。
可以多new几个,zss1,zss2,zss3,按顺序嵌套就 可以了。这个嵌套是精髓