async和await

59 阅读1分钟

代码演示async/await 的用法

//异步加载图片
function loadImg(src) {
    // 使用 promise 对象包装图片加载
    const promise = new Promise((resolve, reject) => {
        const img = document.createElement('img')
        img.onload = () => {
            resolve(img)
        }
        img.onerror = () => {
            reject(new Error(`图片加载失败 ${src}`))
        }
        img.src = src
    })
    
    // 返回 该promise对象
    return promise
}

// 加载图片1
async function loadImg1() {
    const src1 = 'http://www.imooc.com/static/img/index/logo_new.png'
    const img1 = await loadImg(src1) //await相当于then
    return img1
}
 
// 加载图片2
async function loadImg2() {
    const src2 = 'https://avatars3.githubusercontent.com/u/9583120'
    const img2 = await loadImg(src2) //await相当于then
    return img2
}

(async function () {

    // 注意:await 必须放在 async 函数中,否则会报错
    try {
        // 加载第一张图片
        const img1 = await loadImg1()
        console.log(img1)
        // 加载第二张图片
        const img2 = await loadImg2()
        console.log(img2)
    } catch (ex) {
        console.error(ex)
    }
})()

注意

  • asyncawait 搭配使用
  • asyncawait是用同步的方式去实现异步,但是异步本质上还是回调函数async/await 只是es6提供的语法糖
  • async 函数返回结果都是 Promise 对象(如果函数内没返回 Promise ,则自动封装一下)
  • await相当于promise.then 方法
  • await 必须放在 async 函数中,否则会报错
  • try...catch捕获异常,相当于promise.catch
(async function () {
    const p4 = Promise.reject('some err')
    try {
        const res = await p4
        console.log(res)
    } catch (ex) {
        console.error(ex)
    }
})()
  • await 后面跟 Promise 对象会阻断后续代码,等待状态变为 resolved ,才获取结果并继续执行
  • await 后续跟非 Promise 对象会直接返回
(async function () {
    const p1 = new Promise(() => {})
    await p1
    console.log('p1') // 不会执行
})()

(async function () {
    const p2 = Promise.resolve(100)
    const res = await p2
    console.log(res) // 100
})()

(async function () {
    const res = await 100
    console.log(res) // 100
})()

(async function () {
    const p3 = Promise.reject('some err')
    const res = await p3
    console.log(res) // 不会执行
})()
  • 只要遇到了 await后面的代码都相当于放在 callback 里
async function async1 () {
  console.log('async1 start')
  await async2()
  console.log('async1 end')  // 关键在这一步,它相当于放在 callback 中,最后执行
}

async function async2 () {
  console.log('async2')
}

console.log('script start')  
async1()
console.log('script end')


输出结果:
script start
async1 start
async2
script end
async1 end