promise用于异步调用
//基本用法
let ajax=function(){ console.log("执行"); return new Promise(function(resolve,reject){ setTimeout(function(){ resolve() },1000) }) } ajax().then(function(){ console.log("promise","timeout"); })
//连续调用
let ajax=function(){ console.log("执行1"); return new Promise(function(resolve,reject){ setTimeout(function(){ resolve() },1000) }) } ajax() .then(function(){ return new Promise(function(resolve,reject){ setTimeout(function(){ resolve() },2000) }) .then(function(){ console.log("timeout3") }) })
//错误捕获
let ajax=function(num){ console.log("执行乐乐乐"); return new Promise(function(resolve,reject){ if(num>5){ resolve() }else{ throw Error("出错了"); } }) } ajax(6).then(function(){ console.log("执行第二步"); }).catch(function(err){ console.log("catch",err); }) ajax(1).then(function(){ console.log("执行第二步"); }).catch(function(err){ console.log("catch",err); })
原文:http://www.cnblogs.com/karila/p/7874316.html