Recipe 1.4

Using the async and await Keywords

This example shows the basics of working with a Promise based API. It has a getUsers function which simulates a network request with a delay.

When the Promise is resolved, the user list is rendered. This example uses the await keyword instead of calling then on the Promise.

Demo

First name Last name Department
Loading...
Loading Users

Code

JavaScript
async function renderUsers() {
  try {
    // Equivalent to getUsers().then(...)
    const userList = await getUsers();
    const tableBody = document.querySelector('#users tbody');
    userList.forEach(user => {
      renderUser(user, tableBody);
    });
  } catch (error) { // Equivalent to .catch(...)
    console.error('Failed to load user list:', error);
  }
}

renderUsers();

/**
 * Renders a user object as a row in the user table.
 * @param user the user object to render
 * @param tableBody the table body to append the row to
 */
function renderUser(user, tableBody) {
  const row = document.createElement('tr');
  
  const firstName = document.createElement('td');
  firstName.textContent = user.firstName;
  row.appendChild(firstName);

  const lastName = document.createElement('td');
  lastName.textContent = user.lastName;
  row.appendChild(lastName);

  const department = document.createElement('td');
  department.textContent = user.department;
  row.appendChild(department);

  tableBody.appendChild(row);
}

/**
 * Retrieves an array of users after simulating a network request delay.
 * @returns a Promise that resolves to the users array
 */
function getUsers() {
  const users = [
    { firstName: "John", lastName: "Smith", department: "Sales" },
    { firstName: "Emily", lastName: "Johnson", department: "Marketing" },
    { firstName: "Michael", lastName: "Davis", department: "Human Resources" },
    { firstName: "Sarah", lastName: "Thompson", department: "Finance" },
    { firstName: "David", lastName: "Wilson", department: "Engineering" }
  ];    

  return new Promise(resolve => {
    // Use setTimeout to simluate request delay
    setTimeout(() => {
      document.querySelector('#loader').remove();
      resolve(users);
    }, 1500);
  });
}
HTML
<table id="users" class="table">
  <thead>
    <tr>
      <th class="w-25">First name</th>
      <th class="w-25">Last name</th>
      <th class="w-25">Department</th>
    </tr>
  </thead>
  <tbody>
    <tr id="loader">
      <td colspan="3" class="text-center p-4">
          <div class="spinner-border" role="status">
            <span class="visually-hidden">Loading...</span>
          </div>
          <div>Loading Users</div>
      </td>
    </tr>
  </tbody>
</table>
Web API Cookbook
Joe Attardi