Mastering the Fundamentals of JavaScript: A Beginner's Guide to Web Development

 Chapter 9: JavaScript Promises


In this chapter, we will discuss JavaScript promises.


Asynchronous Programming:


JavaScript is a single-threaded language, which means that it can only execute one task at a time. Asynchronous programming allows us to perform multiple tasks simultaneously by letting the program continue running while it waits for a long-running task to complete.


Promises:


A promise is an object that represents the eventual completion or failure of an asynchronous operation. Promises are a way to handle asynchronous code in a more structured and readable way.


Here is an example of a promise:


```

var promise = new Promise(function(resolve, reject) {

  setTimeout(function() {

    resolve("Success!");

  }, 1000);

});


promise.then(function(result) {

  console.log(result); // "Success!"

});

```


In this example, we have created a promise that will resolve with the value "Success!" after a delay of 1000 milliseconds. We have attached a `.then()` method to the promise, which will be called when the promise is resolved. The `result` parameter in the `.then()` function will contain the resolved value of the promise.


Promise States:


A promise can be in one of three states: pending, fulfilled, or rejected.


- Pending: the initial state, neither fulfilled nor rejected.

- Fulfilled: the state representing a successful completion of the asynchronous operation.

- Rejected: the state representing a failure or error in the asynchronous operation.


Chaining Promises:


Promises can be chained together to create more complex asynchronous operations. Each `.then()` method returns a new promise that can be used in the next `.then()` method.


Here is an example of chaining promises:


```

var promise = new Promise(function(resolve, reject) {

  setTimeout(function() {

    resolve(1);

  }, 1000);

});


promise.then(function(result) {

  console.log(result); // 1

  return result + 1;

}).then(function(result) {

  console.log(result); // 2

  return result + 1;

}).then(function(result) {

  console.log(result); // 3

});

```


In this example, we have created a promise that will resolve with the value 1 after a delay of 1000 milliseconds. We have then chained three `.then()` methods together, each of which adds 1 to the result of the previous `.then()` method.


Conclusion:


JavaScript promises are a powerful tool for handling asynchronous code in a structured and readable way. By understanding promise states, chaining promises, and error handling, we can create more efficient and reliable asynchronous operations in our web applications.

Comments