原生JS模拟Promise实现异步编程
1 function ajaxA(success){ 2 setTimeout(function(){ 3 console.log("AAAAAAAAAA"); 4 success(); 5 }, 3000); 6 } 7 8 function ajaxB(success){ 9 setTimeout(function(){ 10 console.log("BBBBBBBBBB"); 11 success(); 12 }, 2000); 13 } 14 15 function ajaxC(success){ 16 setTimeout(function(){ 17 console.log("CCCCCCCCCC"); 18 success(); 19 }, 1000); 20 } 21 22 function ajaxD(){ 23 setTimeout(function(){ 24 console.log("DDDDDDDDD"); 25 }, 2000); 26 }
//模拟异步编程效果 27 function MyPromise(func){ 28 var self = this; 29 var count = 0; 30 this.cbklist = []; 31 this.then = function(callback){ 32 this.cbklist.push(callback); 33 return this; 34 } 35 this.success = function(){ 36 if(count == self.cbklist.length) return; 37 self.cbklist[count++](self.success); 38 } 39 setTimeout(function(){ 40 func(self.success); 41 },0); 42 } 43 //强制程序按then的顺序执行 44 new MyPromise(ajaxA).then(ajaxB).then(ajaxC).then(ajaxD);
运行结果如下:
用代码书写精彩人生