async function getData() {
console.log(1);
const response = await fetch("https://api.apiopen.top/getJoke?page=1&count=2&type=video",
{
mode: 'cors',
headers: {
'Content-Type': 'application/json'
}
});
console.log(2);
return response.json();
}
getData()
.then(res => {
console.log(res);
console.log(3);
})
console.log(4); // 1 4 2 3
async 函数总是会返回 Promise 对象,Promise.then() 回调方法的参数是 async 函数 return 的值。
async 函数在执行时会在 await 关键字语句挂起暂停执行,等待 await 右边的异步方法完成后再以 Promise.then() 的形式执行内部下面的语句,虽然会阻塞 await 下面的代码执行,但是并不会阻塞外部主线程方法的执行。