async & await 用法

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 下面的代码执行,但是并不会阻塞外部主线程方法的执行。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容