Jump to content

JavaScript/Async/Exercises

From Wikibooks, open books for an open world

Topic: Asynchronous functions




1. Define a function that

  • reads the users via the jsonplaceholderapi of the previous page
  • shows all ten usernames together with their hometown
  • include log-messages to observe the program flow
Click to see solution
"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");

Expected output:

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