前言
在 JavaScript 中,异步编程是非常重要的,它可以帮助我们避免阻塞主线程。Promise 是 ES6 引入的一种异步编程解决方案,它使得异步操作变得更加优雅,但是它也有一些缺点,比如代码量比较多,有时候也比较难以理解。ES8 引入了 async/await,它可以让我们更加简单地处理异步操作。在本文中,我们将会介绍如何使用 async/await 替换 Promise。
Promise 的缺点
在使用 Promise 的过程中,我们经常会遇到一些问题。首先,Promise 的链式调用使得代码变得比较冗长,比如下面这个例子:
fetch('https://api.github.com/users')
.then(res => res.json())
.then(users => {
console.log(users);
})
.catch(err => {
console.error(err);
});其次,Promise 的错误处理也比较麻烦,我们需要在每一个 then 方法中都写上一个 catch 方法,这样才能捕获到错误。比如下面这个例子:
// www.javascriptcn.com code example
fetch('https://api.github.com/users')
.then(res => res.json())
.then(users => {
console.log(users);
throw new Error('something went wrong');
})
.then(() => {
console.log('this will not be executed');
})
.catch(err => {
console.error(err);
});最后,Promise 的 then 方法中只能返回一个 Promise 对象,这使得我们有时候需要进行一些额外的操作,比如下面这个例子:
// www.javascriptcn.com code example
fetch('https://api.github.com/users')
.then(res => res.json())
.then(users => {
console.log(users);
const userPromises = users.map(user => {
return fetch(`https://api.github.com/users/${user.login}`)
.then(res => res.json());
});
return Promise.all(userPromises); // 需要额外的 Promise.all 操作
})
.then(userInfos => {
console.log(userInfos);
})
.catch(err => {
console.error(err);
});async/await 的优点
async/await 是 ES8 引入的一种异步编程解决方案,它可以让我们更加简单地处理异步操作。async/await 的语法非常简单,我们只需要在函数前面加上 async 关键字,然后在异步操作前面加上 await 关键字即可。比如下面这个例子:
// www.javascriptcn.com code example
async function fetchUsers() {
const res = await fetch('https://api.github.com/users');
const users = await res.json();
console.log(users);
const userPromises = users.map(async user => {
const res = await fetch(`https://api.github.com/users/${user.login}`);
return res.json();
});
const userInfos = await Promise.all(userPromises);
console.log(userInfos);
}我们可以看到,使用 async/await 可以让我们的代码变得更加简洁和易于理解。
async/await 的错误处理
在使用 async/await 的过程中,我们也需要进行错误处理。与 Promise 不同的是,我们可以使用 try/catch 来捕获错误。比如下面这个例子:
// www.javascriptcn.com code example
async function fetchUsers() {
try {
const res = await fetch('https://api.github.com/users');
const users = await res.json();
console.log(users);
const userPromises = users.map(async user => {
const res = await fetch(`https://api.github.com/users/${user.login}`);
return res.json();
});
const userInfos = await Promise.all(userPromises);
console.log(userInfos);
} catch (err) {
console.error(err);
}
}async/await 的兼容性
虽然 async/await 是 ES8 中的新特性,但是它已经被所有主流浏览器所支持,包括 IE11。如果你需要在旧版浏览器中使用 async/await,你可以使用 Babel 来进行转译。
结语
在本文中,我们介绍了如何使用 async/await 替换 Promise。我们可以发现,async/await 可以让我们的代码变得更加简洁和易于理解,同时也可以更好地处理错误。如果你还没有开始使用 async/await,现在就是时候开始尝试了。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d10704a941bf7134236a29