持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第10天,点击查看活动详情
前言
async 和 await 虽说是es8新特性,可是都es13了,一拖再拖,不能再拖了
这篇文章学习一下 ES8 新特性 async 和 await
async 函数
async 函数有以下特点
-
async 函数的返回值为 promise 对象,
-
promise 对象的结果由 async 函数执行的返回值决定
通过代码验证
第一种情况. 当返回的结果不是一个 Promise 类型的对象时, 则函数返回的结果是成功的 Promise 对象
<script>
//async 函数
async function fn(){
return '晴天蜗牛';
// return;
// return [1,2,3]
}
const result = fn();
console.log(result)
</script>
返回字符串/undefind/array ... 非Promise类型的对象
第二种情况. 抛出错误, 返回的结果是一个失败的 Promise
<script>
//async 函数
async function fn(){
throw new Error('出错啦!');
}
const result = fn();
console.log(result)
</script>
第三种情况. 返回的结果如果是一个 Promise 对象
<script>
//async 函数
async function fn(){
return new Promise((resolve, reject)=>{
resolve('成功的数据');
// reject("失败的错误");
});
}
const result = fn();
console.log(result)
</script>
async函数返回Promise对象,我们可以通过其调用then方法获取其成功或失败的回调
result.then(value => {
console.log(value);
}, reason => {
console.warn(reason);
})
await 表达式
await 表达式有以下特点
-
await 必须写在 async 函数中
-
await 右侧的表达式一般为 promise 对象
-
await 返回的是 promise 成功的值
-
await 的 promise 失败了, 就会抛出异常, 需要通过 try...catch 捕获处理
<script>
//创建 promise 对象
const p = new Promise((resolve, reject) => {
resolve("用户数据");
// reject("失败啦!");
})
// await 要放在 async 函数中.
async function main() {
try {
let result = await p;
//
console.log(result);
} catch (e) {
console.log(e);
}
}
//调用函数
main();
</script>
async 和 await 结合实践
例子1
//1. 引入 fs 模块
const fs = require("fs");
//读取『为学』
function readWeiXue() {
return new Promise((resolve, reject) => {
fs.readFile("./resources/为学.md", (err, data) => {
//如果失败
if (err) reject(err);
//如果成功
resolve(data);
})
})
}
function readChaYangShi() {
return new Promise((resolve, reject) => {
fs.readFile("./resources/插秧诗.md", (err, data) => {
//如果失败
if (err) reject(err);
//如果成功
resolve(data);
})
})
}
function readGuanShu() {
return new Promise((resolve, reject) => {
fs.readFile("./resources/观书有感.md", (err, data) => {
//如果失败
if (err) reject(err);
//如果成功
resolve(data);
})
})
}
//声明一个 async 函数
async function main(){
//获取为学内容
let weixue = await readWeiXue();
//获取插秧诗内容
let chayang = await readChaYangShi();
// 获取观书有感
let guanshu = await readGuanShu();
console.log(weixue.toString());
console.log(chayang.toString());
console.log(guanshu.toString());
}
main();
例子2
<script>
// 发送 AJAX 请求, 返回的结果是 Promise 对象
function sendAJAX(url) {
return new Promise((resolve, reject) => {
//1. 创建对象
const x = new XMLHttpRequest();
//2. 初始化
x.open('GET', url);
//3. 发送
x.send();
//4. 事件绑定
x.onreadystatechange = function () {
if (x.readyState === 4) {
if (x.status >= 200 && x.status < 300) {
//成功啦
resolve(x.response);
}else{
//如果失败
reject(x.status);
}
}
}
})
}
//promise then 方法测试
// sendAJAX("https://api.apiopen.top/getJoke").then(value=>{
// console.log(value);
// }, reason=>{})
// async 与 await 测试 axios
async function main(){
//发送 AJAX 请求
let result = await sendAJAX("https://api.apiopen.top/getJoke");
//再次测试
let tianqi = await sendAJAX('https://www.tianqiapi.com/api/?version=v1&city=%E5%8C%97%E4%BA%AC&appid=23941491&appsecret=TXoD5e8P')
console.log(tianqi);
}
main();
</script>
总结
async 和 await 结合 让异步代码像同步代码一样实现,灵活应用,其乐无穷