跳到内容

JavaScript/异步/练习

来自维基教科书,一个开放世界的开放书籍

主题:异步函数




1.定义一个函数

  • 通过上一页的jsonplaceholderapi读取用户
  • 显示所有十个用户名以及他们的家乡
  • 引入日志消息以观察程序流程
单击查看解决方案
"use strict";

console.log("Start of script");

async function getUserAndTown() {
  console.log("Start of function");
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/users');
    const users = await response.json();
    for (const user of users) {
      console.log(user.name + " / " + user.address.city);  // or: alert(..)
    }        
  } catch (err) {
    console.log('Some error occurred: ' + err.message);
  }
  console.log("End of function");
}

console.log("Calling function");
getUserAndTown();

console.log("End of script");

预期输出

Start of script
Calling function
Start of function
End of script
Leanne Graham / Gwenborough
Ervin Howell / Wisokyburgh
Clementine Bauch / McKenziehaven
Patricia Lebsack / South Elvis
Chelsey Dietrich / Roscoeview
Mrs. Dennis Schulist / South Christy
Kurtis Weissnat / Howemouth
Nicholas Runolfsdottir V / Aliyaview
Glenna Reichert / Bartholomebury
Clementina DuBuque / Lebsackbury
End of function
华夏公益教科书