回调函数的另外一种原生实现,比以前回调函数的写法机构清晰,功能强大,
function a(fn){ let h = 1; setTimeout(function(){ if(h==1){ fn(h) }else{ throw Error('error!') } },1000) } //调用 a(function(m){ console.log(m+'callback') })
function a(){ return new Promise(function(resole,reject){ setTimeout(function(){ if(h==1){ resole(h) }else{ reject(error) } },1000) }) } //调用 a().then(function(data){ console.log(data) },function(err){ console.log(err) })
//函数封装 function fn(n,callback){ setTimeout(function(){ callback(n) },1000) } function fn2(m,callback){ setTimeout(function(){ callback(m) },800) } function fn3(h,callback){ setTimeout(function(){ callback(h) },600) } //多层回调调用 fn(1, function(n){ console.log('fn='+n); fn2(2,function(n2){ console.log('fn2='+n2); fn3(3,function(n3){ console.log('fn3='+n3) console.log('end') }) }) });
可见(1)中多层回调写起来很乱,不利于维护,下面用Promise实现编程
function pm(n){ return new Promise(function(resolve,reject){ setTimeout(function(){ if(n){ resolve(n) }else{ reject(error) } },1000) }) } function pm2(n){ return new Promise(function(resolve,reject){ setTimeout(function(){ if(n){ resolve(n) }else{ reject(error) } },1000) }) } function pm3(n){ return new Promise(function(resolve,reject){ setTimeout(function(){ if(n){ resolve(n) }else{ reject(error) } },1000) }) } //调用 pm(1).then(function(data){ console.log('pm='+data); return pm2(2) }).then(function(data){ console.log('pm2='+data); return pm3(3) }).then(function(data){ console.log('pm3='+data); })
用promise调用的写法更加直观promise
(1)异步编程思想来写同步代码 (2)遍历器生成函数 (3)状态机,封装了多个内部状态。
function* abc(){ //yield 非必须,return 也非必须; yield 'a'; yield 'b'; return 'c' } //调用 var h = abc(); h.next();//{value:'a',done:false} h.next();//{value:'b',done:false} h.next();//{value:'c',done:true} h.next();//{value:undefined,done:true}
function pm(n){ return new Promise((resolve,reject)=>{ setTimeout(function(){ console.log(n) resolve() },1000) }) } function pm2(n){ return new Promise((resolve,reject)=>{ setTimeout(function(){ console.log(n) resolve() },800) }) } function pm3(n){ return new Promise((resolve,reject)=>{ setTimeout(function(){ console.log(n) resolve() },600) }) } function* gPm(){ yield pm(1); yield pm2(2); yield pm3(3); } let p = gPm(); p.next().value.then(function(){ p.next().value.then(function(){ p.next().value.then(function(){ }) }) })
在调用的时候用Generator函数;代码更加同步化异步
(1)异步操做的终极解决方案
function pm(n){ return new Promise((resolve,reject)=>{ setTimeout(function(){ console.log(n) resolve() },1000) }) } function pm2(n){ return new Promise((resolve,reject)=>{ setTimeout(function(){ console.log(n) resolve() },800) }) } function pm3(n){ return new Promise((resolve,reject)=>{ setTimeout(function(){ console.log(n) resolve() },600) }) } async function p(){ await pm(1) await pm2(2) await pm3(3) } p()
无论用then仍是用generator 仍是用async,都保证你写的function 的返回值是一个 promise对象