写法不同
ES5
正常的写法getAjax(url,(res)=>{})
Promise
写法getAjax(url).then((res)=>{})
Async
写法
总结:// 异步async函数调用后也是一个Promise对象 (async ()=>{ let res=await getAjax(url) })()
ES5
写法会造成回调地狱,代码可读性差;Promise
写法让回调函数划分出去,避免了函数回调地狱,提高代码可读性;Async
写法是Promise
的语法糖,使得代码回归正常,阅读性高,更加简洁,底层编译会自动转换为Promise
的写法
Promise实现原理
-
定义一个类
class Promise{ // 定义构造函数 constructor(fn){ // 成功事件集成在successList数组里 this.successList=[] // 失败事件集成在failList数组里 this.failList=[] // 定义状态 this.state='pending' // 传入的函数对象(异步操作的函数内容) fn(this.resolveFn.bind(this),this.rejectFn.bind(this)) } // 2. 传入成功或者失败时执行的函数 then(successFn,failFn){ if(typeof successFn=='function'){ this.successList.push(successFn) } if(typeof failFn=='function'){ this.failList.push(failFn) } } catch(failFn){ if(typeof failFn=='function'){ this.failList.push(failFn) } } // 定义调用成功和失败的函数 resolveFn(res){ this.state='fullfilled' // 调用成功后的事件 this.successList.forEach((item,index)={ item(res) }) } rejectFn(res){ this.state='rejected' // 调用失败后的事件 this.failList.forEach((item,index)={ item(res) }) throw Error(res) } }
-
应用
function fsRead(path){ return new Promise(function(resolve,reject){ fs.readFile(path,{flag:'r',encoding:'utf-8'},(err,data)=>{ if(err){ reject(err) }else{ resolve(data) } }) }) }