Using Promises for Better Flow Control

Tutorial 2 of 5

Using Promises for Better Flow Control

1. Introduction

Goal

This tutorial aims to teach you how to use Promises in JavaScript for better flow control and handling of asynchronous operations.

Learning Objectives

By the end of this tutorial, you will be able to:
- Understand what Promises are and how they work
- Use Promises to handle asynchronous operations
- Create smoother flow control in your JavaScript code

Prerequisites

  • Basic knowledge of JavaScript
  • Understanding of asynchronous programming concepts

2. Step-by-Step Guide

Understanding 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 future result, allowing you to write asynchronous code in a more synchronous fashion.

A Promise is in one of these states:
- Pending: initial state, neither fulfilled nor rejected.
- Fulfilled: the operation completed successfully.
- Rejected: the operation failed.

Creating a Promise

A Promise is created using the new Promise() constructor which takes a single argument, an executor function that itself takes two parameters, resolve and reject. The function is executed immediately by the Promise implementation, passing resolve and reject functions.

let promise = new Promise(function(resolve, reject) {
  // asynchronous operation code
});

Using Promises

You can use the then() method to schedule code to run when the Promise resolves. then() takes two optional arguments, both are callback functions for the success and failure cases respectively.

promise.then(
  function(result) { /* handle a successful operation */ },
  function(error) { /* handle an error */ }
);

3. Code Examples

Example 1: Simple Promise

This code creates a Promise that resolves after a specified amount of time.

let timeoutPromise = new Promise(function(resolve, reject) {
  // Set a timeout for 1 second
  setTimeout(function() {
    resolve('Promise resolved'); // After 1 second, we resolve the promise
  }, 1000);
});

// Use the promise
timeoutPromise.then(
  function(message) {
    console.log(message); // Prints: Promise resolved
  },
  function(error) {
    console.log(error);
  }
);

Example 2: Promise that can reject

This code creates a Promise that can either resolve or reject based on a condition.

let conditionalPromise = new Promise(function(resolve, reject) {
  let condition = true; // Change this to see different results

  if (condition) {
    resolve('Condition is true');
  } else {
    reject('Condition is false');
  }
});

// Use the promise
conditionalPromise.then(
  function(message) {
    console.log(message); // Prints: Condition is true
  },
  function(error) {
    console.log(error); // If condition is false, this will be printed
  }
);

4. Summary

In this tutorial, we've learned:
- What a Promise is and how it works in JavaScript
- How to create and use Promises to handle asynchronous operations
- How to use Promises for better flow control

Next, you can learn more about advanced Promise concepts like chaining and error handling. See the MDN Guide on Using Promises for more information.

5. Practice Exercises

  1. Create a Promise that resolves with a string after 3 seconds. Print the string when the Promise resolves.
  2. Create a Promise that rejects with an error. Use then() to handle the error.
  3. Create a function that returns a Promise. The Promise should resolve if the function is passed a number, and reject otherwise.

Remember to use the Promise constructor and the then() method. Happy coding!