ES8 中的 async/await——JavaScript 异步编程的完美解决方案
在日常前端开发中,我们时常会用到异步编程,而在 JavaScript 中,其异步编程多用 Promise,而 Promise 又被显得繁琐。ES8 中新增了 async/await 这一语法糖,是 Promise 的一种更简洁、易读、易维护的封装,让异步编程体验更加友好。
一、async/await 的基本用法
1.async 关键字
- async 关键字声明一个异步函数
async function exampleFunc() {
// do something
}- async 函数内部的内容会自动封装成一个 Promise 对象,即使函数本身不返回 Promise
2.await 关键字
- await 关键字用于等待异步操作的结果,并返回一个 resolved 的 Promise 对象
async function exampleFunc() {
let result = await promiseFunc()
console.log(result)
}- await 关键字只能在 async 函数内使用
二、实例应用
以调取后端 API 接口为例,我们通常会这样写:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data)
})或者使用 async/await:
async function getData() {
const response = await fetch('https://api.example.com/data')
const data = await response.json()
console.log(data)
}在这个例子中,使用 async/await 可以使代码更加简洁易读,用同步的方式处理异步返回的数据,更加符合人类思维。如果需要串联多个请求,使用 async/await 则更为便捷:
// www.javascriptcn.com code example
async function getData() {
try {
const response1 = await fetch('https://api.example.com/data1')
const data1 = await response1.json()
console.log(data1)
const response2 = await fetch('https://api.example.com/data2')
const data2 = await response2.json()
console.log(data2)
} catch (error) {
console.error(error)
}
}可以看到,使用 async/await 的代码不仅更简洁易读,还更加易于错误处理。
三、注意事项
在使用 async/await 时,需要注意以下几点:
1.异步函数内部无法通过 throw 抛出错误,必须使用 try...catch 来捕获错误和异常
2.如果一个 async 函数中有多个 await,它们之间是并行的
3.如果多个 async 函数串联,可以在函数内使用 await 调用其他异步函数
4.返回一个 rejected 的 Promise,可以自动抛出错误,无需使用 throw
5.如果一次请求依赖于前一次请求的结果,可以将请求放在 Promise 中,再使用 async/await 进行处理
// www.javascriptcn.com code example
function getData1() {
return fetch('https://api.example.com/data1').then(response => response.json())
}
function getData2(data1) {
return fetch(`https://api.example.com/data2/${data1}`).then(response => response.json())
}
async function getData() {
try {
const data1 = await getData1()
const data2 = await getData2(data1)
console.log(data1, data2)
} catch (error) {
console.error(error)
}
}async/await 在 JavaScript 中异步编程的应用相对于 Promise 更为简洁、易读和易维护。在实际开发中,可以根据具体需求进行选择。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67cfa2cae46428fe9eb57302