Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

What are promises in JavaScript

Before understanding what are promises in JavaScript, Let’s understand the execution flow in the JavaScript. In general, the JavaScript execution model is synchronous as it is a single-threaded.

What are promises in JavaScript

Javascript can execute one task at a time, apart from that it provides some methods like promises and callback, and that can help you to execute your code in an asynchronous approach.

What are promises in JavaScript?

Promises are objects represents the eventual completion/failure of an asynchronous operation and its resulting value.

How do promises work in javascript?
Promises can be created by the keyword new and its constructor.

const APIgetPosts = new Promise(function(resolve, reject) {

 // call for an api to get the posts
 // resolve(successResponse); // executed successfully

 // or
 // reject(failureResponse); // rejected

});

 

As shown above, the constructor takes an argument, but this is not a just argument instead it is called as “executor function”. And this execution function will be having two parameters resolve and reject as a function.
Resolve: This function will be called when the asynchronous task has been executed successfully and returns the result of the task as a response object value.
Reject: This function will be called when the asynchronous task execution fails and returns an error object as a reason.
Let’s take below example,

// promise function to read API
function APIgetPosts(url) {
 // Return new promise 
 return new Promise(function(resolve, reject) {
 // Do async job
 var xhr = new XMLHttpRequest();
 xhr.open('GET', url, true);
 xhr.responseType = 'json';
 xhr.onload = function() {
 var status = xhr.status;
 
 if (status === 200) {
 resolve(xhr.response);
 }

 else {
 reject(xhr.status);
 }
 };
 
 xhr.send();

 });
}

let ApiUrl="https://jsonplaceholder.typicode.com/posts";
let initializePromise = APIgetPosts(ApiUrl);

initializePromise.then(function(result) {

 console.log('API data has been retrieved');
 console.log(result);

},
function(err) {

 console.log('Couldnot resolve API');
 console.log('Error => ' + err);
});

// output when success
// API data has been retrieved
// A list of post objects

// output when failure
// Couldnot resolve API
// Error => 404

 

Below is an example of the promise that accepts the API URL and reads the API URL. If the URL returns JSON data then it triggers the resolve function.
And if API is not returning any JSON response then it triggers reject function.

Advantages Of Promises:
Compared to another asynchronous method, the promises have the below rich set of features

States:
Pending: When you initialize promise it will be pending.
Fulfilled: Indicates that the asynchronous task has been executed successfully.
Rejected: Indicates that the asynchronous task failed.

Guarantees:
The promise comes with some guarantees as follows:
The “executor function” will be called only after the completion of the current task.
The “executor function” called callbacks added with then method.
The main feature of the promises is the chaining method.
The chaining methods make handling easy.

Chaining method:
Chaining method helps in executing more than one asynchronous task. In other words back to back.

new Promise((resolve, reject) => {

 console.log('Initial');
 resolve(); 

})
.then(() => {

 throw new Error('Something failed');
 console.log('Do this');

})
.catch(() => {
 
 console.error('Do that');

})
.then(() => {

 console.log('Do this, no matter what happened before');

});

// otuput
// Initial
// Do that
// Do this, no matter what happened before

 

Also, read What is closure in JavaScript?