代码演示async/await 的用法
function loadImg(src) {
const promise = new Promise((resolve, reject) => {
const img = document.createElement('img')
img.onload = () => {
resolve(img)
}
img.onerror = () => {
reject(new Error(`图片加载失败 ${src}`))
}
img.src = src
})
return promise
}
async function loadImg1() {
const src1 = 'http://www.imooc.com/static/img/index/logo_new.png'
const img1 = await loadImg(src1)
return img1
}
async function loadImg2() {
const src2 = 'https://avatars3.githubusercontent.com/u/9583120'
const img2 = await loadImg(src2)
return img2
}
(async function () {
try {
const img1 = await loadImg1()
console.log(img1)
const img2 = await loadImg2()
console.log(img2)
} catch (ex) {
console.error(ex)
}
})()
注意
async
和await
搭配使用
async
和await
是用同步
的方式去实现异步
,但是异步本质上还是回调函数
,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)
})()
(async function () {
const res = await 100
console.log(res)
})()
(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')
}
async function async2 () {
console.log('async2')
}
console.log('script start')
async1()
console.log('script end')
输出结果:
script start
async1 start
async2
script end
async1 end