async 函数和await 表达式细节说明
一、async/await 方式和Promise 方式发送 Ajax请求
1.1、定义一个发送请求的函数
函数返回一个 Promise 对象。
function sendAjax(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
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);
}
}
}
})
}
1.2、Promise.then()方式
接受异步操作的执行结果。
sendAjax('https://api.apiopen.top/getJoke').then(value=>{
console.log(value);
}, reason => {
})
1.3、async/await 方式
获取异步操作的执行结果。
async function sendmsg() {
let daunzi = await sendAjax('https://api.apiopen.top/getJoke');
console.log(daunzi)
}
sendmsg();
二、async/await 结合使用的必要
async 关键字不过是一个标识符,如果异步函数中没有await关键字,其执行与普通函数没什么区别。
2.1、同步执行
async function foo() {
console.log(2);
}
console.log(1);
foo();
console.log(3);
####### 执行结果 ######
1
2
3
2.2、await 可以暂停异步函数的执行:一
async function foo() {
console.log(2);
await null;
console.log(4);
}
console.log(1);
foo();
console.log(3);
####### 执行结果 ######
1
2
3
4
2.3、await 可以暂停异步函数的执行:二
async function foo2() {
console.log(2);
console.log(await 4);
}
console.log(1);
foo2();
console.log(3);
####### 执行结果 ######
1
2
3
4
2.4、await 可以暂停异步函数的执行v:三
async function foo() {
console.log(2);
console.log(await Promise.resolve(6));
console.log(7);
}
async function bar() {
console.log(4);
console.log(await 8);
console.log(9);
}
console.log(1);
foo();
console.log(3);
bar();
console.log(5);
####### 执行结果 ######
1
2
3
4
5
6
7
8
9