86264153 2019-06-21
使用Promise可以避免回调函数的层层嵌套,还提供了规范更加容易的对异步操作进行控制。提供了reject,resolve,then和catch等方法
Promise有三种状态:
挂起状态 成功状态 失败状态
Promise是ES6之后原生的对象,我们只需要实例化Promise对象就可以直接使用。实例化Promise:
var p = new Promise(function(resolve,refused){ console.log("abc");//abc //resolve(); setTimeout(function(){ resolve(); },3000)//定时器 console.log("123"); }); p.then(function(){ console.log("dfe")//用resolve()执行 });*/
setTimeout(function(){ console.log(1); setTimeout(function(){ console.log(2) setTimeout(function(){ console.log(3); },3000) },2000) },1000);*/ var p1=new Promise(function(resolve,refused){ setTimeout(function(){ resolve() },1000); }); p1.then(function(){ console.log(1); /*return new Promise(function(resolve,refused){ setTimeout(function(){ resolve(); },2000); });*/ return sleep(2000); }).then(function(){ console.log(2); /*return new Promise(function(resolve,refused){ setTimeout(function(){ resolve(); },3000); });*/ return sleep(3000); }).then(function(){ console.log(3); }); function sleep(times){ return new Promise(function(resolve,refused){ setTimeout(function(){ resolve(); },2000); }); } var pp=new Promise(function(resolve,refused){ //resolve() refused(); });
成功之后执行then方法
/*pp.then(function(){ console.log("dddfff") })
失败之后执行catch方法
pp.catch(function(){ console.log("llll") })