一、常用方式
var state=false; var p =new Promise((success,fail)=>{ if(state){ success("执行成功"); }else{ fail("执行失败"); } }) p.then(res=>{ console.log(res); }).catch(res=>{ console.log(res); })
var get_all_thing=""; function p1(){ return new Promise(give_you_something=>{ setTimeout(()=>{ var time=new Date().getMinutes()+" : "+new Date().getSeconds()+"\n"; give_you_something(time) },3000) }) } function p2(){ return new Promise(give_you_something=>{ setTimeout(()=>{ var time=new Date().getMinutes()+" : "+new Date().getSeconds()+"\n"; give_you_something(time) },3000) }) } function p3(){ return new Promise(give_you_something=>{ setTimeout(()=>{ var time=new Date().getMinutes()+" : "+new Date().getSeconds()+"\n"; give_you_something(time) },3000) }) } function p4(){ return new Promise(give_you_something=>{ setTimeout(()=>{ var time=new Date().getMinutes()+" : "+new Date().getSeconds()+"\n"; give_you_something(time) },3000) }) } p1().then(res=>{ get_all_thing+=res; return p2(); }).then(res=>{ get_all_thing+=res; return p3(); }).then(res=>{ get_all_thing+=res; return p4(); }).then(res=>{ get_all_thing+=res; console.log(get_all_thing); })
function p1(arg){ return new Promise(give_you_something=>{ setTimeout(()=>{ var time=new Date().getMinutes()+" : "+new Date().getSeconds()+"\n"; arg+=time; give_you_something(arg) },3000) }) } function p2(arg){ return new Promise(give_you_something=>{ setTimeout(()=>{ var time=new Date().getMinutes()+" : "+new Date().getSeconds()+"\n"; arg+=time; give_you_something(arg) },3000) }) } function p3(arg){ return new Promise(give_you_something=>{ setTimeout(()=>{ var time=new Date().getMinutes()+" : "+new Date().getSeconds()+"\n"; arg+=time; give_you_something(arg) },3000) }) } function p4(arg){ return new Promise(give_you_something=>{ setTimeout(()=>{ var time=new Date().getMinutes()+" : "+new Date().getSeconds()+"\n"; arg+=time; give_you_something(arg) },3000) }) } p1("").then(res=>{ return p2(res); }).then(res=>{ return p3(res); }).then(res=>{ return p4(res); }).then(res=>{ console.log(res); })
二、then方法
// then()返回值仍为promise对象 let p1 = new Promise((success, fail) => { success(123) }).then(res => { return 123 }) p1.then(res => { console.log(res) return new Promise((success, fail) => { success(456) }) // 等价于return 456 }).then(res => { console.log(res) })