当前位置:网站首页>ES8 | async and await
ES8 | async and await
2022-08-08 08:04:00 【Cai Cai who doesn't like vegetables】
async和await
async和await两种语法结合可以让异步代码像同步代码一样
async函数
async函数的返回值是promise对象
promise对象的结果由async函数执行的返回值决定
1.返回的结果不是一个promise类型的对象,The return result of this function is a successPromise对象
<script>
async function fn() {
// 返回一个字符串
return 'HAHA';
}
const result = fn();
console.log(result);
</script>

2. 抛出错误,返回的结果是一个失败的Promise
<script>
async function fn() {
// 抛出错误,返回的结果是一个失败的Promise
throw new Error('出错了')
}
const result = fn();
console.log(result);
</script>

3. 返回的结果是一个Promise对象,如果Promise是成功的,Then the function returns something successful
如果是失败的,It returns the content of failure
<script>
async function fn() {
// 返回的结果是一个Promise对象
return new Promise((resolve,reject)=>{
// resolve('成功的数据');
reject('失败了');
})
}
const result = fn();
console.log(result);
</script>


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); // await 返回的是promise 成功的值,A failed value is not returned
} catch (e) {
// await 的promise 失败了,就会抛出异常,需要通过try...catch捕获处理
console.log(e);
}
}
// 调用函数main
main();
</script>
async 和await 结合读取文件
// 1. 引入fs模块
const {
log } = require('console');
const fs = require('fs');
// 2. 读取【为学】
// 返回的都是promise对象
function readWeiXue() {
return new Promise((resolve, reject) => {
fs.readFile('./resources/为学.md', (err, data) => {
// 如果失败
if (err) reject(err);
// 如果成功
resolve(data);
})
})
}
// 3. 读取【插秧诗】
// 返回的都是promise对象
function readChaYangShi() {
return new Promise((resolve, reject) => {
fs.readFile('./resources/插秧诗.md', (err, data) => {
// 如果失败
if (err) reject(err);
// 如果成功
resolve(data);
})
})
}
// 4. 读取【观书有感】
// 返回的都是promise对象
function readGuanShu() {
return new Promise((resolve, reject) => {
fs.readFile('./resources/观书有感.md', (err, data) => {
// 如果失败
if (err) reject(err);
// 如果成功
resolve(data);
})
})
}
// 声明一个async函数
async function main() {
// read as learning content
let weixue = await readWeiXue(); // The return value is the success value
// Read the content of the rice-planting poem
let chayang = await readChaYangShi(); // The return value is the success value
// Read the book with a sense of content
let guanshu = await readGuanShu(); // The return value is the success value
console.log(weixue.toString());
console.log(chayang.toString());
console.log(guanshu.toString());
}
main();
async 和await 结合发送ajax 请求
<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 方法测试
const result = sendAJAX("https://api/apiopen.top/getJoke").then(value => {
console.log(value);
}, reason => {
})
// async 与 await 测试
async function main() {
// 发送Ajax请求
let result = await sendAJAX("https://api/apiopen.top/getJoke");
console.log(result);
}
main();
</script>
边栏推荐
猜你喜欢
随机推荐
2022/8/7
动手学线性代数
CoCube显示测试笔记
BLOB, TEXT, GEOMETRY or JSON column ‘xxxx‘ can‘t have a default value
Spiral Matrix
物联网安全系列 - 非对称加密算法 ECDH
生成密码字典的方法
业内首个「因果推断全流程」挑战赛!WAIC 2022 · 黑客马拉松邀全球开发者精英来挑战
【vulhub】PostGresql高权限命令执行漏洞复现(CVE-2019-9193)
under项目under项目
设计圆类,求圆的周长
教你实现多线程案例定时器
DBeaver 22.1.4 released, a visual database management platform
C#实现在企业微信内发送消息给指定人员帮助类
Gatsby精粹,面向未来的blog
Task02:PyTorch进阶训练技巧
[Regression prediction] Gaussian process regression based on GPML toolbox with matlab code
物联网安全-消息认证码
最强分布式锁工具:Redisson
lvm creates logical volumes









