一、开心一下

这是一个令人非常激动的早晨,2020年12月25日,我终于把 Promise 的 async 和 await 搞清楚了一些,能把 MDN 上的例子完全看懂了,async和await:让异步编程更简单

它的例子还涉及到 fetch API,我一直在想 fetch 后为什么要两个 then,原来因为 json() 方法返回的是一个 Promise 对象,如果你对 response 直接打印,那它是一个对象

二、两个使用的例子

使用 async、await 的实践

  1. async function showGithubApi(){
  2. let response = await fetch('https://api.github.com')
  3. let apiContent = await response.json()
  4. console.log(apiContent)
  5. }
  6. showGithubApi().catch(console.log)

使用用 async 和 await 语法对于 fetch JSON数据的封装

  1. async function fetchJSON(url){
  2. let response = await fetch(url)
  3. return await response.json()
  4. }
  5. fetchJSON('https://api.github.com').then(console.log).catch(console.log)

「@浪里淘沙的小法师」