JavaScript Promises provide cleaner and more intuitive way to deal with asynchronous code. This tutorial will help you understand what Promises are and how to create them. You will also learn how to use them with handler functions. At the end, you will also learn how to handle multiple Promises.

Introduction

What are JavaScript promises? Promises are objects that represent some value. You don’t know that value when you create a Promise. You will get this value in the future when a promise is resolved or rejected. Code that follows the Promise is not block by it. This makes writing asynchronous code much easier and more manageable.

Imagine you have an app. When you start this app it needs to fetch data from some API. The problem is that you don’t know when you will receive this data. Sometimes, you get them quickly. Sometimes, it might take more time. How can you write your app in a way so it takes this uncertainty into account?

One option could be checking the data in specific intervals. You would do this until you finally get the data you need. This is neither effective nor clean. Another option is to use a Promise. You can use a Promise to make that API call. When this Promises is settled, that is it is resolved or rejected, you can update your app.

How is this easier? When JavaScript Promise is settled, resolved or rejected, it automatically triggers events you can listen to with specific handler methods. With that, you don’t have to regularly check the status of Promises like in the first solution.

Instead, your handlers will automatically execute any code you want at the right moment when Promise returns some value. I hope this makes sense.

Creating a Promise

That was the theory. Now, to the practice. When you want to create a Promise you use Promise constructor. In the terms of syntax, this means using keyword new followed by Promise(). The constructor takes one parameter. This parameter is a function called executor. The executor is invoked automatically when you create a Promise.

The executor function takes two parameters, both of which are callbacks. These parameters are resolve and reject. When Promise is resolved the resolve callback is invoked. This is when the job a Promise is supposed to do is successful. When it is not, when there is some error, Promise is rejected and the reject callback is invoked.

// Promise syntax example
const myPromise = new Promise(function(resolve, reject) {
  // ... some code
})

// Promise syntax example using an arrow function
const myPromise = new Promise((resolve, reject) => {
  // ... some code
})

#javascript #javascript promises

JavaScript Promises - All You Need to Know to Get Started
1.10 GEEK