重学ES6(九)async/await

303 阅读2分钟

基础用法

async/await 其实是 promise 的语法糖,它能实现的效果都能用 promise 来实现,它就是为了用来优化 promise 的 then 链而开发的。

async 是异步的简写,await是等待,所以我们很好理解 async 声明的 function 是异步的,await 等待某个操作完成。语法上强制规定 await只能出现再 async 函数中。

function timeout(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms)
    })
}

async function asyncPrint(value, ms) {
    await timeout(ms)
    console.log(value)
}

asyncPrint('hello', 1000)

async 函数返回的是 Promise 对象,可以作为 await 的参数

async function timeout(ms) {
    await new Promise((resolve) => {
        setTimeout(resolve, ms)
    })
}

async function asyncPrint(value, ms) {
    await timeout(ms)
    console.log(value)
}

asyncPrint('hello', 1000)

async 函数有多种使用形式

// 函数式声明
async function foo () {}

// 函数表达式
const foo = async function() {}

// 对象的方法
let obj = {
	async foo () {}
}
obj.foo().then(...)

// class 的方法
class Storage {
	constructor() {
    	this.cachePromise = cache.open('avatars')
    }
    
    async getAvatar(name) {
    	const cache = await this.cachePromise
         return cache.match(`/avatars/${name}.jpg`)
    }
}

const storage = new Storage();
storage.getAvatar('jake').then(…)

// 箭头函数
const foo = async () => {}

async 函数返回一个 Promise 对象。

async 函数内部 return 语句返回的值,会成为 then 方法返回调函数的参数。

async function f() {
	return 'hello world'
}

f().then(val => console.log(val))
// 'hello world'

async 函数内部抛出错误,会导致返回的 Promise 对象变为 reject status。判处错误对象会被 catch 方法回调函数接收

async function f() {
  throw new Error('出错了');
}

f().then(
  v => console.log('resolve', v),
  e => console.log('reject', e)
)

//reject Error: 出错了

await 命名后面式一个 Promise 对象,返回该对象的解构。如果不是 Promise 对象,就直接返回对应的值。

async function f() {
    // return 123
    return await 123
}

f().then(v => console.log(v))
// 123

javascript 没有sleep的语法,但是使用 await 可以让程序停留指定的时间

function sleep (interval) {
    return new Promise(resolve => {
        setTimeout(resolve, interval)
    })
}

async function oneSleepAsync() {
    for (let i = 0; i < 5; i++) {
        console.log(i)
        await sleep(1000)
    }
}

oneSleepAsync()

await 命令后面的 Promise 对象如果变为 reject 状态,则 reject 参数会被 catch 方法回调函数接收

async function f() {
    await Promise.reject('error')
}

f().then( v=> console.log(v))
    .catch(e => console.log(e))
// error