一、async 与 await
async 函数,如下所示:
- 函数的返回值为
promise 对象 promise 对象的结果由 async 函数执行的返回值决定
await 表达式,如下所示:
await 右侧的表达式一般为 promise 对象, 但也可以是其它的值- 如果表达式是
promise 对象, await 返回的是 promise 成功的值 - 如果表达式是其它值, 直接将此值作为
await 的返回值
- 注意点,如下所示:
await 必须写在 async 函数中, 但 async 函数中可以没有 await- 如果
await 的 promise 失败了, 就会抛出异常, 需要通过 try...catch 捕获处理
二、async 与 await 的使用
async 函数,代码如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>async 函数</title>
</head>
<body>
<script>
async function main () {
throw 'error';
}
let result = main();
console.log(result);
</script>
</body>
</html>
await 函数,代码如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>await 函数</title>
</head>
<body>
<script>
async function main () {
let p = new Promise((resolve, reject) => {
reject('error');
});
try {
let res3 = await p;
}catch(e) {
console.log(e);
}
}
main();
</script>
</body>
</html>
async 与 await 的结合,代码如下所示:
const fs = require('fs');
const util = require('util');
const mineReadFile = util.promisify(fs.readFile);
async function main () {
try {
let data1 = await mineReadFile('./resource/1.html');
let data2 = await mineReadFile('./resource/2.html');
let data3 = await mineReadFile('./resource/3.html');
console.log(data1 + data2 + data3);
} catch (e) {
console.log(e.code);
}
}
main();
async 与 await 结合发送 ajax,代码如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>async与await结合发送ajax</title>
</head>
<body>
<button id="btn">点击获取段子</button>
<script>
function sendAJAX (url) {
return new Promise((resolve, rejecy) => {
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open('GET', url);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
} else {
reject(xhr.status);
}
}
}
});
}
let btn = document.querySelectorAll('#btn');
btn.addEventListener('click', async function () {
let duanzi = await sendAJAX('https://api.apiopen.top/getJoke');
console.log(duanzi);
});
</script>
</body>
</html>