首先,思路来自于 http://www.cnblogs.com/liuliang-wifi/p/6832850.html。这篇文章写的很好,相比而言这篇文章是更有难度一点的,有兴趣的可以欣赏一下这篇文章。链接:点击打开链接
其次,这个问题来自于阿里一面的姐姐问道的。
当时我的回答是调用Promise函数来实现,面试姐姐希望我实现一下Promise函数,我回忆起阮一峰教程里是通过Generator函数实现的。但是面试姐姐更希望用javascript原生实现,我当时脑子一个懵,心里其实是有思路的,但是当时卡住不知道如何回答,哈哈。所以今天就整理了一下。
代码如下:
function ajax1( that){ setTimeout( function(){ console. log( 'I am ajax1!'); that. count++; if( that. finalCall && that. count === that. leng){ that. fun(); } }, 1000); } function ajax2( that){ setTimeout( function(){ console. log( 'I am ajax2!'); that. count++; if( that. finalCall && that. count === that. leng){ that. fun(); } }, 2000); } function ajax3( that){ setTimeout( function(){ console. log( 'I am ajax3!'); that. count++; if( that. finalCall && that. count === that. leng){ that. fun(); } }, 3000); } function Promise(){ if(! this instanceof Promise) return; var that = this; that. count = 0; that. leng = arguments. length; that. finalCall = false; that. then = function( fun){ that. finalCall = true; that. fun = fun; }; for( var i = 0; i < that. leng; i++){ arguments[ i]( that); } } new Promise( ajax1, ajax2, ajax3). then( function(){ console. log( 'I am final!'); });
代码难度不大,所以就不解释了。这个实现方案我并不是很满意,若有其它思路,愿意和我分享的话,希望你可以留言,互相学习一下拉~
ps:文章开头提到的文章,若你理解有困难,可以简单的这样理解。主要是通过 链式调用 和 回调函数的一种递归形式的调用。若留言指出有理解不正确的地方,我会十分开心!谢谢观看!