Async Programming

Tutorial 4 of 4

Async Programming: A Tutorial

1. Introduction

Tutorial's Goal

This tutorial aims to provide a comprehensive understanding of asynchronous (async) programming, with a focus on its application in web development using JavaScript.

Learning Outcomes

By the end of this tutorial, you will:

  1. Understand the fundamental concepts of async programming.
  2. Learn how to implement async operations in JavaScript.
  3. Be able to write and understand async functions, promises, and the async/await syntax in JavaScript.

Prerequisites

A basic understanding of JavaScript and HTML is required for this tutorial. Familiarity with ES6 syntax would be beneficial but not strictly necessary.

2. Step-by-Step Guide

What is Async Programming?

Async programming allows you to perform lengthy operations without blocking the execution of your code. In the world of web development, this means your web app can continue to respond to user input while performing other tasks, such as fetching data from an API.

Promises

A Promise in JavaScript is an object representing the eventual completion or failure of an asynchronous operation. It serves as a placeholder for the result of the async operation. A Promise is in one of these states:

  • Pending: The Promise's outcome hasn't yet been determined.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

Here's a basic example of a Promise:

let promise = new Promise((resolve, reject) => {
    let condition = true;
    if(condition) {
        resolve('Promise is fulfilled');
    } else {
        reject('Promise is rejected');
    }
});

promise.then((message) => {
    console.log(message); // Promise is fulfilled
}).catch((message) => {
    console.log(message);
});

Async/Await

Async/Await is a modern syntax that makes working with Promises more comfortable and less error-prone. An async function is a function declared with the async keyword, and the await keyword can only be used within an async function.

Here's an example:

async function fetchData() {
    try {
        let response = await fetch('https://api.example.com/data');
        let data = await response.json();
        console.log(data);
    } catch (error) {
        console.error('Error:', error);
    }
}
fetchData();

3. Code Examples

Example 1: Basic Promise

// A simple Promise that resolves after a set time
let timeoutPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("Completed!"); // Promise is fulfilled after 2 seconds
    }, 2000);
});

// Using the Promise
timeoutPromise.then((message) => {
    console.log(message); // Outputs: "Completed!"
});

Example 2: Async/Await

async function fetchUsers() {
    try {
        let response = await fetch('https://jsonplaceholder.typicode.com/users');
        let users = await response.json();
        console.log(users); // Outputs: Array of user data
    } catch (error) {
        console.error('Error:', error);
    }
}
fetchUsers();

4. Summary

In this tutorial, we've covered the basics of async programming in JavaScript, including promises and the async/await syntax. Understanding these concepts will allow you to create more efficient and responsive web applications.

For further learning, consider delving into more complex topics such as Promise chaining and error handling in async functions.

5. Practice Exercises

Exercise 1

Create a Promise that resolves with the string "Hello, World!" after 1 second, then logs the message to the console.

Solution

let helloPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("Hello, World!");
    }, 1000);
});

helloPromise.then((message) => {
    console.log(message); // Outputs: "Hello, World!"
});

Exercise 2

Rewrite the following Promise-based code using async/await syntax:

fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));

Solution

async function fetchPost() {
    try {
        let response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
        let data = await response.json();
        console.log(data);
    } catch (error) {
        console.error('Error:', error);
    }
}
fetchPost();

We hope this tutorial has provided you with a solid foundation for async programming in JavaScript. Happy coding!