async/await

  1. 异步回调 callback hell
  2. promise then catch 链式调用,也是基于回调函数
  3. async/await是同步语法,完全消灭回调函数
//promise加载图片
function loadImg(src){
    new Promise((resolve,reject)=>{
        const img = document.createElement("img")
        img.onload = () => {
            resolve(img)
        }
        img.onerror = () => {
            const error = new Error(`图片加载失败${src}`)
            reject(error)
        }
        img.src = src
    })
}
const src = "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2111934553,104502141&fm=26&gp=0.jpg"

!(async function(){
    const img1 = await loadImg(src)
    console.log(img1.height,img1.width)
})()

async/await 和 promise的关系

async/await是消灭异步回调的终极武器
  • 执行async函数,返回的是Promise对象
  • await至关于Promise的then
  • try...catch可捕获异常,代替了Promise的catch
async function fn1(){
    return 100 ;   //至关于return Promise.resolve(100)
}
const  res1 = fun1() //执行async函数,返回一个Promise对象
console.log('res1',res1)
res1.then(data=>{
    console.log('data',data) //100
})

!(async function(){
    const p1 = Promise.resolve(300)
    const data = await p1
    console.log('data',data); //300
})()

!(async function(){
    const data1 = await fn1()
    console.log('data1',data1) //100
})()

!(async function(){
    const p4 = Promise.reject('err1')
    try{
        const res = await p4
        console.log(res) 
    } catch (ex) {
        console.error(ex)//err1
        //try...catch至关于promise的catch
    }
})()
  
  
!(async function(){
    const p5 = Promise.reject('err2')//rejected状态->catch
    const data5 = await p5 //await至关于then
    console.log(data5)//控制器会报错
})()
相关文章
相关标签/搜索