1 min read

What are promises in javascript

Promises are used for better handling of asynchronous operations and improves code readability.
What are promises in javascript

Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.

Events were not good at handling asynchronous operations.

Promises are the ideal choice for handling asynchronous operations in the simplest manner. They can handle multiple asynchronous operations easily and provide better error handling than callbacks and events.

Promise has four states:

  1. fulfilled: Action related to the promise succeeded
  2. rejected: Action related to the promise failed
  3. pending: Promise is still pending i.e not fulfilled or rejected yet
  4. settled: Promise has fulfilled or rejected

var promise = new Promise(function(resolve, reject){

//do something

});

A promise can be created using Promise constructor.

Example:

var promise = new Promise(function(resolve, reject) {
const x = "geeksforgeeks";
const y = "geeksforgeeks"
if(x === y) {
resolve();
} else {
reject();
}
});

promise.
then(function () {
console.log('Success, You are a GEEK');
}).
catch(function () {
console.log('Some error has occured');
});

output: Success, You are a GEEK

Read more about Promise Consumers..

JavaScript | Promises - GeeksforGeeks
A computer science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
https://www.geeksforgeeks.org/javascript-promises/

#javascript #Programming #Promises #Objects #Probyto #ProbytoAI

Subscribe and follow us for latest news in Data Science and Machine learning and stay updated!
Facebook: https://facebook.com/probyto
Twitter: https://twitter.com/probyto
LinkedIn: https://linkedin.com/company/probyto
Instagram: https://instagram.com/probyto