首页 > 代码库 > waterfall实现

waterfall实现

 1 function TaskRun(tasks,done)
 2 {
 3     var task_index=0;
 4     done=done||((err)=>{
 5         err&&console.log(err);
 6     });
 7     function next()    {
 8         if(task_index==tasks.length) {return done(null);}
 9         var args=[].slice.call(arguments);
10         args.push(next);
11         try{
12             tasks[task_index++].apply(this,args);
13         }catch(ex){
14             return done(ex);
15         }
16     }
17     next(); 
18 }
19 
20 TaskRun([function(next){
21     setTimeout(function(){
22         console.log("one");
23          next(1);
24      }, 10);
25     
26 },function(num1,next){
27     console.log("two");
28     console.log(num1);
29     throw new Error("sfdsf");
30     setTimeout(function(){
31         console.log("last");
32          next(3,4);
33      }, 10);
34 },function(num1,num2,next){
35     console.log("5");
36     console.log(num1);
37     console.log(num2);
38 }])

 

waterfall实现