How do you create a promise in JavaScript?

Table of Contents

Introduction

A promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation. Promises provide a cleaner alternative to callbacks, making it easier to work with asynchronous code.

Creating a Promise

Syntax

To create a promise, you use the Promise constructor, which takes a function (known as the executor) that has two parameters: resolve and reject. The resolve function is called when the operation completes successfully, while reject is called if the operation fails.

Example

Here’s a simple example of creating a promise:

In this example:

  • The promise checks a condition (success).
  • If the condition is true, it calls resolve, passing a success message.
  • If the condition is false, it calls reject, passing an error message.

Using the Promise

To handle the result of a promise, you use the .then() and .catch() methods:

Explanation:

  • .then(result => {...}) is executed if the promise is resolved.
  • .catch(error => {...}) is executed if the promise is rejected.

Conclusion

Creating a promise in JavaScript is straightforward and enhances the handling of asynchronous operations. By using the Promise constructor along with resolve and reject, you can manage success and error scenarios effectively, leading to cleaner and more readable code.

Similar Questions