Explanation of Promise in JavaScript

Explanation of Promise in JavaScript

Hello everyone, in this article we are going to talk about Promise usage in JavaScript. We are going to learn promise and we will make examples for better understanding.

Let's begin...

We can perform asynchoronous operations with promise in JavaScript. Promise let us know the operation is successful or not with using operation states.

Below you can see the states of a promise pipeline
  • fulfilled : The promise operation is successfull
  • rejected : The promise operation has a fault during execution.
  • pending : The promise operation is not completed yet.
  • settled : The promise operation is completed but result is not important
Below image you can see a simple lifecycle schema of Promise in JavaScript. Simple Lifecycle of Javascript Promise

As you can see at above image initial state is pending state. After execution, if operation is completed successful state is fullfilled otherwise it will be rejected. If it is reusable it will be pending state again. Also as we can see after pending, both fullfilled and rejectedstates are called as settled state.

Let's create a promise. Below code block you can see syntax.

const promise = new Promise(function(fullfilledHandler, rejectedHandler){
     //some operations
});

fullfilledHandler and rejectedHandler functions are callbacks and we send the functions as callbacks for execution in related states. It will execute the fullfilledHandler if result is successful, it will execute rejectedHandler if operation is failed.

Below you can see a simple example of Promise in JavaScript

let state = true;
control().then(function(res) {
	console.log("promise handled Result is : " + res);
});

function control() {
	return new Promise(function(resolve,reject) {
		setTimeout(function() {
			if(state){
				resolve("successfull")
			}
			else{
				reject("error occured")
			}
		},5000);
	});
}
After 5 seconds the Promise will run asynchoronously. In google developer console you can see below result. Simple JavaSciprt Promise Example output

In above example we also chained the promise. Now take a look at the promise chaining.

Promise chaning is a way to execute multiple asynchronous tasks within promises. We used then(...) method to perform chain promise operations. We can also use catch() and finally() functions to perform exeption handling after executing a promise. If promise rejected we use catch() and if promise completed anyway we use finally() method.

then()
We can invoke the new tasks with promise chaining. We use then method to invoke next function.

then method is belong to Promise class. So the function must return the Promise for calling the then(). then() method also returning new promise

Below you can see the usage of then.

init_chain().then(function(param) {
	console.log("first promise called Parameter is : " + param );
})
.then(another_promise())
.then(fun())
.then(another_function());

function init_chain() {
	return new Promise(function(resolve,reject) {
		resolve("successfull");
	});
}

function another_promise() {
	return new Promise(function(resolve,reject) {
		resolve("successfull");
	});
}

function fun(){
	console.log("promise called " );
}

function another_function(){
	console.log("another function");
}
Below image you can see the example output Javascript promise then method example output
catch()

catch() method in promise is used to invoke a task when an error occured or promise rejected.

Below you can see the example of catch method()

let state = false;
control().then(function(res) {
	console.log("promise handled Result is : " + res);
}).catch(function(res) {
	console.log("catch block invoked data is : " + res);
});

function control() {
	return new Promise(function(resolve,reject) {
		setTimeout(function() {
			if(state){
				resolve("successfull")
			}
			else{
				reject("error occured")
			}
		},1000);
	});
}
Program output will be

catch block invoked data is : error occured
finally()

finally() method being invoked when the promise is either fullfilled or rejected. finally block will be invoked whatever the state is.


let thepromise= new Promise(function (resolve, reject) {
    resolve('fullfilled'); 
});

let thepromise2= new Promise(function (resolve, reject) {
    reject('rejected'); 
});

thepromise.finally(function () {
        console.log("Finally block invoked from resolved ");
    }
);

thepromise2.finally(function () {
        console.log("Finally block invoked from rejected ");
    }
).catch(function(){
        console.log("promise is rejected ");
});
Program output will be below Javascript promise finally example output

That is all in this article.

Have a good promising

Burak Hamdi TUFAN


Tags


Share this Post

Send with Whatsapp

Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment.

Comments

  • There is no comment. Be the owner of first comment...