标签:
第零步
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>链式化</title> <script type="text/javascript"> (function(){ function Promise(fn){ var instance = this; instance["_value"] = ""; var resolve = function(val){ instance["_value"] = val; }; fn(resolve); } var promise_proto = Promise.prototype; promise_proto.then = function(successFn){ var instance = this; return new Promise(function(resolve){ var resolveWrapper = function(val){ var ret = successFn(val); if(typeof(ret) != "undefined" && ret.constructor === Promise){ ret.then(function(info){ resolve(info); }); } else{ return ret; } } resolveWrapper(instance["_value"]); }); }; window.Promise = Promise; })(); (function(){ return new Promise(function(resolve){ resolve(1); }) })() .then(function(info){ return new Promise(function(resolve){ console.log(info); resolve(2); }) }) .then(function(info){ console.log(info); }); </script> </head> <body> new Promise返回一个新空间P1, P1里面有匿名函数function(resolve){resolve(1);}) 和 匿名函数 function(info){ console.log(info); return new Promise(function(resolve){ resolve(2); }) } P1运动方式: 1.内部生成resolve函数,并注入到第一个匿名函数,也就是resolve(1)。执行resolve(1),也就是把1赋值给P1里面的一个变量_value。 2.把_value注入到第二个匿名函数,然后执行第二个匿名函数,根据第二个匿名函数返回是否为Promise类型,来觉得下一步。 </body> </html>
标签:
原文地址:http://www.cnblogs.com/samwu/p/4693463.html