Promise是为了解决多层回调函数嵌套结构太深,代码逻辑不符合线性流程的问题。线性流程问题是解决了的,但是嵌套结构太深(每多一层回调就多一层缩进)感觉并没有解决。
在不提取函数的情况下,串行异步加载3张图片的传统代码如下:
var img1 = new Image(); img1.onload=function (){ var img2 = new Image(); img2.onload=function (){ var img3 = new Image(); img3.onload=function (){ console.log("ended"); }; img3.src="http://img1.bdstatic.com/static/home/widget/search_box_home/logo/home_white_logo_0ddf152.png"; }; img2.src="http://www.baidu.com/img/bd_logo.png"; }; img1.src="http://www.baidu.com/img/bd_logo1.png";
用Promise之后的代码如下:
new Promise(function (resolve, reject) { var img1 = new Image(); img1.onload=function (){ resolve(); }; img1.src="http://www.baidu.com/img/bd_logo1.png"; }).then(function (){ new Promise(function (resolve, reject) { var img2 = new Image(); img2.onload=function (){ resolve(); }; img2.src="http://www.baidu.com/img/bd_logo.png"; }).then(function (){ new Promise(function (resolve, reject) { var img3 = new Image(); img3.onload=function (){ resolve(); }; img3.src="http://img1.bdstatic.com/static/home/widget/search_box_home/logo/home_white_logo_0ddf152.png"; }).then(function (){ console.log("ended"); }); }); });
可以看到代码顺序是得到纠正了,但是加载第3张图片的代码仍然有3个缩进。
如果还是用传统的方法,但是提取函数的话,也可以让代码的逻辑稍微调整得更易读些,缩进问题也解决了,代码如下:
function step1(){ var img1 = new Image(); img1.onload=function (){ step2(); }; img1.src="http://www.baidu.com/img/bd_logo1.png"; } function step2(){ var img2 = new Image(); img2.onload=function (){ step3(); }; img2.src="http://www.baidu.com/img/bd_logo.png"; } function step3(){ var img3 = new Image(); img3.onload=function (){ console.log("ended"); }; img3.src="http://img1.bdstatic.com/static/home/widget/search_box_home/logo/home_white_logo_0ddf152.png"; } step1();
刚接触Promise,对它了解不多,不知道是不是还有更好的写法。