# My JavaScript Learning Journey - Week 8: Promises, Async/Await and Error Handling

As I continue learning JavaScript, I am gradually moving towards concepts that help me understand how JavaScript handles operations behind the scenes.

During my previous weeks, I explored topics such as [DOM manipulation](https://dharmapadadalai.hashnode.dev/javascript-learning-journey-array-methods-to-dom-manipulation), events, APIs and XMLHttpRequest. This week, I focused on another important part of JavaScript: Promises and Error Handling.

From Day 42 to Day 45, I explored how to resolve Promises with different types of values, access their results, work with Promise Chaining and use Async/Await.

I also learned different ways to handle errors using .catch(), try...catch, finally and throw.

Some of these concepts were new to me, so I spent time understanding them through simple examples.

Here is what I learned during this week.

## Day 42: Resolving Promises with Objects and Arrays

On Day 42, I practised resolving a Promise with different types of values, including objects and arrays.

Before this, I was familiar with the basic idea of a Promise, but I wanted to understand how to access data when a Promise resolves with something more than a simple string or number.

### What is a Promise?

A Promise is a JavaScript object that represents the eventual success or failure of an asynchronous operation.

A Promise has three possible states:

1. Pending: The operation is still in progress.
2. Fulfilled: The operation completed successfully.
3. Rejected: The operation failed.

For example:

```javascript
const myPromise = new Promise((resolve, reject) => {
  resolve("Promise resolved successfully!");
});

myPromise.then((result) => {
  console.log(result);
});
```

**Output:**

```plaintext
Promise resolved successfully!
```

Here, resolve() is used to fulfil the Promise with a value and .then() is used to handle the fulfilled result.

### Resolving a Promise with an Object

A Promise can also be resolved with an object.

```javascript
const userPromise = new Promise((resolve, reject) => {
  resolve({
    name: "Dharmapada",
    role: "Full-Stack Developer",
    learning: "JavaScript"
  });
});

userPromise.then((user) => {
  console.log(user);
  console.log(user.name);
  console.log(user.learning);
});
```

**Output:**

```plaintext
{
  name: "Dharmapada",
  role: "Full-Stack Developer",
  learning: "JavaScript"
}

Dharma
JavaScript
```

Here, the Promise resolves with an object containing three properties.

Inside .then(), I can access the resolved object and its properties just like a normal JavaScript object.

### Resolving a Promise with an Array

Similarly, a Promise can be resolved with an array.

```javascript
const skillsPromise = new Promise((resolve, reject) => {
  resolve(["HTML", "CSS", "JavaScript", "React"]);
});

skillsPromise.then((skills) => {
  console.log(skills);
  console.log(skills[0]);
  console.log(skills[2]);
});
```

**Output:**

```plaintext
["HTML", "CSS", "JavaScript", "React"]

HTML
JavaScript
```

This helped me understand that the resolved value does not have to be a string. It can also be an object, an array or another value.

**My takeaway:** I learned how to work with different types of data returned by a Promise and access that data using .then().

## Day 43: Understanding Promise Chaining and Async/Await

On Day 43, I explored three related concepts:

- JavaScript Promises
- Promise Chaining
- Async/Await

These concepts helped me understand different ways of working with asynchronous operations.

### What is Promise Chaining?

Promise Chaining means connecting multiple .then() methods so that one operation can use the result of the previous operation.

Let's understand this with a simple example.

```javascript
const myPromise = new Promise((resolve, reject) => {
  resolve(10);
});

myPromise
  .then((value) => {
    console.log(value);
    return value * 2;
  })
  .then((value) => {
    console.log(value);
    return value + 5;
  })
  .then((value) => {
    console.log(value);
  });
```

**Output:**

```plaintext
10
20
25
```

Here is what happens:

1. The Promise resolves with the value 10.
2. The first .then() receives 10 and returns 20.
3. The second .then() receives 20 and returns 25.
4. The third .then() receives 25 and displays it.

One important thing I learned is that .then() returns a new Promise. This allows us to connect multiple .then() methods together.

This makes it possible to handle a sequence of asynchronous operations.

### What is Async/Await?

After exploring Promise Chaining, I learned about async and await.

Async/Await provides another way to work with Promises. It makes asynchronous code easier to read by allowing us to write it in a style that looks more like regular, sequential JavaScript.

Let's look at an example:

```javascript
function getUser() {
  return new Promise((resolve, reject) => {
    resolve("Dharmapada");
  });
}

async function displayUser() {
  const user = await getUser();

  console.log(user);
}

displayUser();
```

**Output:**

```plaintext
Dharmapada
```

Let's understand the two keywords.

1. async

The async keyword is used before a function declaration to make it an async function.

An async function always returns a Promise.

2. await

The await keyword is used to wait for a Promise to settle.

If the Promise is fulfilled, await gives us its fulfilled value. If the Promise is rejected, await throws the rejection reason.

In this example, await getUser() waits for the Promise to resolve before assigning its result to the user variable.

One important point I learned is that await is normally used inside an async function. JavaScript also supports top-level await in modules.

### Promise Chaining vs Async/Await

Both approaches help us work with Promises, but their syntax is different.

| Promise Chaining | Async/Await |
| --- | --- |
| Uses .then() | Uses async and await |
| Connects operations through Promise methods | Makes asynchronous code look more sequential |
| Can be useful for chaining Promise results | Often easier to read when several steps depend on each other |

For me, Async/Await was interesting because the code looked more straightforward.

I am still practising both approaches, but understanding how they work has made asynchronous JavaScript a little clearer.

## Day 44: Handling Promise Errors Using .catch() and try...catch

On Day 44, I focused on handling errors in JavaScript Promises.

Until now, I had mainly practised what happens when a Promise is fulfilled. But what happens when something goes wrong?

That is where error handling becomes important.

### 1\. Handling Errors Using .catch()

The .catch() method is used to handle a rejected Promise.

Here is a simple example:

```javascript
const myPromise = new Promise((resolve, reject) => {
  reject("Something went wrong!");
});

myPromise
  .then((result) => {
    console.log(result);
  })
  .catch((error) => {
    console.log(error);
  });
```

**Output:**

```plaintext
Something went wrong!
```

Here, the Promise is rejected using reject().

Because the Promise is rejected, the success handler inside .then() is skipped and the .catch() handler receives the rejection reason.

### 2\. Handling Errors Using try...catch with Async/Await

I also learned how to handle rejected Promises when using Async/Await.

For example:

```javascript
function getData() {
  return new Promise((resolve, reject) => {
    reject("Unable to get data!");
  });
}

async function fetchData() {
  try {
    const result = await getData();

    console.log(result);
  } catch (error) {
    console.log(error);
  }
}

fetchData();
```

**Output:**

```plaintext
Unable to get data!
```

Here, the await expression is inside the try block.

If the Promise is rejected, await throws the rejection reason and the catch block handles it.

This is an important point I learned:

When using Async/Await, put the awaited operation inside a try block if you want its rejection to be handled by the corresponding catch block.

**.catch() vs try...catch**

Both approaches can help us handle Promise errors.

- .catch() is commonly used with Promise Chaining.
- try...catch is commonly used with Async/Await.

I found it helpful to practise both because they allow us to handle errors using different styles.

## Day 45: Understanding JavaScript Error Handling

On Day 45, I explored JavaScript Error Handling in more detail.

I learned about built-in Error Objects, [DOMException](https://developer.mozilla.org/en-US/docs/Web/API/DOMException), Error properties and the try, catch, finally and throw statements.

This helped me understand that JavaScript provides different ways to identify, create and handle errors.

### 1\. Understanding Error Objects

JavaScript provides a built-in Error object that represents an error.

We can create an Error object using the Error constructor.

```javascript
const myError = new Error("Something went wrong!");

console.log(myError.name);
console.log(myError.message);
```

**Output:**

```plaintext
Error
Something went wrong!
```

The Error object can also contain useful information about the error.

### 2\. Important Error Properties

I explored some commonly used Error properties.

| Property | Purpose |
| --- | --- |
| name | Represents the error type or name |
| message | Contains the error description |
| stack | Provides information about where the error occurred |
| cause | Can store the underlying reason for another error |

Here is a small example:

```javascript
const error = new Error("Failed to load data");

console.log(error.name);
console.log(error.message);
console.log(error.stack);
```

The stack property is particularly useful when debugging because it can help us trace where an error occurred.

The cause property is useful when creating a new error while preserving the original reason behind it.

### 3\. What is DOMException?

I also learned about DOMException.

DOMException represents an exception related to certain Web API and DOM operations.

For example, some browser operations can throw a DOMException when an operation cannot be performed.

Here is a simple example:

```javascript
try {
  document.querySelector("#myElement").remove();
} catch (error) {
  console.log(error.name);
  console.log(error.message);
}
```

This example uses try...catch to demonstrate how an exception from a DOM operation can be handled.

The exact error depends on the operation and the situation. Not every DOM-related error is necessarily a DOMException.

### 4\. Understanding try...catch...finally

I also explored the finally block.

JavaScript provides three parts that can be used for error handling:

- try
- catch
- finally

Let's understand them with an example.

```javascript
try {
  console.log("Inside try block");

  throw new Error("Something went wrong!");
} catch (error) {
  console.log("Inside catch block");
  console.log(error.message);
} finally {
  console.log("Inside finally block");
}
```

**Output:**

```plaintext
Inside try block
Inside catch block
Something went wrong!
Inside finally block
```

Here is what each part does:

try: Contains the code that might throw an error.

catch: Handles an error thrown from the corresponding try block.

finally: Executes after the try/catch processing, whether an error occurred or not.

The finally block is useful when we need to perform cleanup or other actions regardless of whether an operation succeeds or fails.

### 5\. Understanding the throw Statement

Another concept I learned was the throw statement.

We can use throw to generate our own errors when a particular condition is not satisfied.

For example:

```javascript
const age = 15;

try {
  if (age < 18) {
    throw new Error("You must be at least 18 years old.");
  }

  console.log("Access granted!");
} catch (error) {
  console.log(error.message);
}
```

**Output:**

```plaintext
You must be at least 18 years old.
```

Here, the throw statement creates an error when the age is below 18.

The error is then handled by the catch block.

This helped me understand that we do not always have to wait for JavaScript or a browser API to produce an error. We can also throw our own errors when needed.

## What I Learned During Week 8

Looking back at these four days, I explored several concepts that are important for working with asynchronous JavaScript and handling unexpected situations.

Here are my main takeaways:

- Learned how to resolve Promises with objects and arrays.
- Practised accessing resolved values using .then().
- Understood the basic idea of Promise Chaining.
- Explored async and await.
- Learned how to handle rejected Promises using .catch().
- Practised using try...catch with Async/Await.
- Explored built-in Error Objects and DOMException.
- Learned about Error properties such as name, message, stack and cause.
- Practised using try, catch, finally and throw.

One thing I realised is that understanding the successful execution of code is only part of learning JavaScript.

We also need to understand what happens when something fails and how to handle those situations properly.

**Also Like:** [My JavaScript Learning Journey - Week 5: Dates, Arrays and Objects](https://dharmapadadalai.hashnode.dev/javascript-learning-journey-week-5-dates-arrays-objects)

## My Thoughts After Week 8

This week introduced me to concepts that I will use in many real-world JavaScript applications.

Promises and Async/Await are especially useful when working with operations such as API requests, where the result may not be available immediately.

Error handling is equally important because applications should be prepared for situations where something does not work as expected.

I am still a beginner, so I know I need more practice with these concepts before I become fully comfortable using them.

But I am happy that I am gradually understanding how these pieces of JavaScript fit together.

My next goal is to practise these concepts more and apply them in small projects rather than only learning them through examples.

45 days completed, but the learning journey continues! 🚀

If you are also learning JavaScript, keep practising one concept at a time. You do not need to understand everything immediately. Try examples, make mistakes, debug your code and keep improving.

Thanks for following my learning journey!
