07 Mar How to write Promises in JavaScript

Almost anyone who has used JavaScript, had a love/hate relationship with it at some point. JavaScript is like that girlfriend who is frustrating at times but has something about her which keeps us intrigued. JavaScript has a galore of interesting topics and concepts to explore. Let’s start with one of them- Promises.

JavaScript is a synchronous programming language, but because of callback functions we can make it work like an Asynchronous Programming language.

Promises

Promises in javascript are very similar to promises made in real life.

Definition of promise -Google

After a promise is made, we get an assurance about ‘something’ and we can plan accordingly.

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

Playing with promises has 2 parts-

Creation of Promises

Handling of Promises

Creation

Promises have the basic blueprint

JavaScript

1

2

3

4

newPromise(/* executor */function(resolve,reject){...});

--MDN

The executing function(executor) accepts two parameters resolve and reject which in turn are callback functions. Promises are used for handling asynchronous operations also called blocking code, examples of which are DB, I/O or API calls, which are carried out by the executor function. Once that completes it either calls resolve on success or reject function on error.

Simple example

JavaScript

1

2

3

4

5

6

7

let promise=newPromise(function(resolve,reject){if(promise_kept)

resolve("done");else

reject(newError("…"));

});

As it can be seen, Promises don’t return values immediately. It waits for the success or failure and then returns accordingly. This lets asynchronous methods return values like synchronous ones. Instead of returning values right away, async methods supply a promise to return the value.

The above paragraph makes one thing clear, It has states!

A promise can be one of these states-

pending — This is the initial state or state during execution of promise. Neither fulfilled nor rejected.

fulfilled — Promise was successful.

rejected — Promise failed.

The states are quite self-explanatory so won’t go in detail. Here is a screenshot for reference.

Handling and Consuming the Promise

In the last section we saw how Promises are created, now let’s see how the promise can be consumed.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

constisDone=newPromise()

//...

constcheckIfDone=()=>{

isDone

.then(ok=>{

console.log(ok)

})

.catch(err=>{

console.error(error)

})

}

Running .checkIfDone() will execute the isDone() promise and will wait for it to resolve, using the then callback. If there is an error it will be handled in the catch block.

Chaining Promises

A promise can be returned to another promise , creating a chain of promises. If one fails all others too. Chaining is very powerful combined with Promise as it gives us the control of the order of events in our code.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

newPromise(function(resolve,reject){

setTimeout(()=>resolve(1),1000);

}).then(function(result){

alert(result);

returnresult*3;

}).then(function(result){

alert(result);

returnresult*4;

}).then(function(result){

alert(result);

returnresult*6;

});

All of the operations return there results to the next then() function on resolve and this process continues till the chain is complete. The last element in the chain return the final result.

Conclusion

This was just a basic gist of JavaScript promises. Promises can do a lot more if used in the right way and the right place.