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/1a.txt');
let data2 = await mineReadFile('./resource/2.txt');
let data3 = await mineReadFile('./resource/3.txt');
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 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, reject) => {
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.querySelector('#btn');
btn.addEventListener('click',async function(){
let duanzi = await sendAJAX('https://api.apiopen.top/getJoke');
console.log(duanzi);
});
</script>
</body>
</html>