一、开心一下
这是一个令人非常激动的早晨,2020年12月25日,我终于把 Promise 的 async 和 await 搞清楚了一些,能把 MDN 上的例子完全看懂了,async和await:让异步编程更简单
它的例子还涉及到 fetch API,我一直在想 fetch 后为什么要两个 then,原来因为 json() 方法返回的是一个 Promise 对象,如果你对 response 直接打印,那它是一个对象
二、两个使用的例子
使用 async、await 的实践
async function showGithubApi(){
let response = await fetch('https://api.github.com')
let apiContent = await response.json()
console.log(apiContent)
}
showGithubApi().catch(console.log)
使用用 async 和 await 语法对于 fetch JSON数据的封装
async function fetchJSON(url){
let response = await fetch(url)
return await response.json()
}
fetchJSON('https://api.github.com').then(console.log).catch(console.log)
「@浪里淘沙的小法师」