async 和 Promise的区别

js 的异步回调

async  await 是基于 Promise 实现的  他不能用于普通的回调函数
async  和  Promise 一样是非阻塞的
async  使异步代码看起来更像同步
makeRequest()
console.log('up')
function MakeRequest (){
    test().then((d)=>{
       console.log(d.data)
    })
}
console.log('down')
显示的顺序是  up   down   请求   请求有延时  无论在哪里执行请求都会在  最后执行打印
async  异步调用

console.log('up')
async function MakeRequest (){
    console.log('beforeDown')
  await  test().then((d)=>{
       console.log(d.data)
    })
    console.log('down')
      await  bean().then((d)=>{
       console.log(d.data)
    })
}
console.log('Footerdown')
MakeRequest ()
 
 显示的顺序是   up Footerdown  beforeDown  请求 down   请求     在async 里面按自上而下  同步执行
错误处理
   try catch   无法拦截到 普通请求 JSON.parse 转化的错误    加上 async  await  就可以拦截
   async function MakeRequest (){
       try{
          await  test().then((d)=>{
                  console.log(JSON.parse(d))
            })
           /* .catch((e)=>{
              console.log(e)
              })*/
     }.catch(e){
           console.log(e)
     }
}
MakeRequest ()

  使用async await   的好处  
  使用async 不需要那么多的箭头函数,可以向调试同步代码一样跳过await  
  语法promise   在then里面  添加断点调试器  不会调到下一个then里面  
  因为他会跳过异步代码

async  function MakeRequest(){
    console.log("up")
    var d=await test()
    console.log(d.data)
    var dd=await bean()
    console.log(dd.data)
    console.log("down")
}
MakeRequest()
执行顺序  up  请求   请求   down     执行顺序按照从上到下执行
Promise  的使用

console.log("before")
new Promise((resolve)=>{
    console.log("upup")
    test().then((d)=>{
        console.log("up1")
        resolve(d.data)
        console.log("up2")
   })
   console.log("beforedown")
}).then((d)=>{
    console.log(data1)
      console.log(d)
     console.log(data2)
})
console.log("down")
执行顺序   beforeup   upup  brforedown   down  up1  up2  data1    resolve返回值  data2    异步请求之外自上而下执行
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章