JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

Day 26: Can You Simplify Async/Await in JavaScript?

Master Asynchronous Programming with Async/Await!

Dipak Ahirav
JavaScript in Plain English
3 min readFeb 3, 2025

Welcome to Day 26 of our JavaScript challenge series! Today, we’ll demystify async/await, a modern approach to handling asynchronous code in JavaScript. By the end of this challenge, you’ll be confident in using async/await to write clean and readable asynchronous functions.

Not a Member? Read for FREE here.

The Challenge

Write an asynchronous function using async/await that:

  1. Fetches data from a public API.
  2. Handles errors gracefully.
  3. Logs the fetched data or an error message.

Here’s the API we’ll use:

https://jsonplaceholder.typicode.com/posts/1

Solution: Understanding Async/Await

Async/await is syntactic sugar over Promises, making asynchronous code look and behave more like synchronous code.

Step 1: Writing the Async Function

Here’s how you can fetch data using async/await:

async function fetchPost() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('Fetched Post:', data);
} catch (error) {
console.error('Error fetching post:', error.message);
}
}

fetchPost();

How It Works

  1. async Keyword:
  • Declares an asynchronous function.
  • Automatically wraps the function’s return value in a Promise.

2. await Keyword:

  • Pauses execution of the async function until the Promise resolves.
  • Can only be used inside an async function.

3. Error Handling:

  • try...catch ensures errors are handled gracefully.

Output

If the fetch request is successful:

{
"userId": 1,
"id": 1,
"title"

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Written by Dipak Ahirav

Full Stack Developer | Angular & MEAN Stack Specialist | MEAN Stack Developer | Blogger | Open to Collaboration Author of "Code & Coffee: A Developer's Journey"

No responses yet

Write a response