异步的问题

function logger() {
    let data = fetch('<http://sampleapi.com/posts>')
    console.log(data) // 结果还没获取到, 输出了个寂寞
}

logger()

asyncawait 标记一下

async function logger() {
    let data = await fetch('<http://sampleapi.com/posts>')
    console.log(data) // 成功输出了数据
}

logger()

Async Await

是Promise 和Generator 的语法糖

处理无法立刻返回结果的请求

await, 比起yield

可以自动执行

可以自动判断异步完成状态

可以自动解析promise (得到response, 得到json ...)

function* g() {
  let jsonUpdateAt = null;
  yield fetch("<https://cat-fact.herokuapp.com/facts/random>")
    .then(response => response.json())
    .then(json => {
      jsonUpdateAt = json.updatedAt;
      console.log("json.text", json.text); // 后执行
    });
  console.log("jsonUpdateAt", jsonUpdateAt) // 先执行, null
}
let iterator = g();
iterator.next();
iterator.next();
async function g() {
  let jsonUpdateAt = null;
  await fetch("<https://cat-fact.herokuapp.com/facts/random>")
    .then(response => response.json())
    .then(json => {
      jsonUpdateAt = json.updatedAt;
      console.log("json.text", json.text); // 先执行
    });
  console.log("jsonUpdateAt", jsonUpdateAt) // 后执行, 成功得到值
}
g();
// 自动解析promise
async function g() {
  let response = await fetch("<https://cat-fact.herokuapp.com/facts/random>")
  let json = await response.json()
  console.log("json.text:", json.text);
  console.log("json.updatedAt:", json.updatedAt)
}
g();

/*
	response.json() 也是异步
	因为一个资源可以分别放在多个resposne 中
	浏览器有了响应数据, 有了response , 但可能只是资源的一部分
	所以还是得异步处理

	<https://css-tricks.com/using-fetch/#li-comment-1608333>
		看评论解了一大疑惑, (✨_✨)
*/

await 要在async 函数中才有效, 在chrome-devtool-console 这样的顶级作用域中也有效

可以await Promise.all()

async function logPosts ()  {
    try {
        let user_id = await fetch(`/api/users/username`)
        let post_ids = await fetch(`/api/posts/<code>${user_id}`)
        let promises = post_ids.map(post_id => {
            return  fetch(`/api/posts/${post_id}`)
        }
        let posts = await Promise.all(promises)
        console.log(posts)
    } catch (error) {
        console.error(`Error:`, error) 
    }
}