Promises in Javascript is an object and represents an Asynchronous operation, It is used to find out if the asynchronous operation is successfully completed or not. The new Javascript APIs are being purely implemented using Promises.
What is a Promise?
A promise in JavaScript is similar to a promise in real life.
A promise may have one of three states.
- Pending: Initial State, before the Promise succeeds or fails
- Resolved: Completed Promise
- Rejected: Failed Promise
A promise starts in a pending state. That means the process is not complete. If the operation is successful, the process ends in a fulfilled state. And, if an error occurs, the process ends in a rejected state. For example, when you request data from the server by using a promise, it will be in a pending state. When the data arrives successfully, it will be in a fulfilled state. If an error occurs, then it will be in a rejected state
Promise Syntax:
let myPromise = new Promise(function(myResolve, myReject) {
// “Producing Code” (May take some time)
myResolve(); // when successful
myReject(); // when error
});
// “Consuming Code” (Must wait for a fulfilled Promise)
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
Program with a Promise :
let completed = true;
let learnJS = new Promise(function (resolve, reject) {
if (completed) {
resolve(“I have completed learning JS.”);
} else {
reject(“I haven’t completed learning JS yet.”);
}
})
What is the difference between Callbacks and Promises?
A key difference between the two is that when using the callbacks approach we would normally just pass a callback into a function which will get called upon completion to get the result of something, whereas in promises you attach callbacks on the returned promise object.
Callbacks:
function getMoneyBack(money, callback) {
if (typeof money !== ‘number’) {
callback(null, new Error(‘money is not a number’))
} else {
callback(money)
}
const money = getMoneyBack(1200)
console.log(money)
Promises:
function getMoneyBack(money) {
return new Promise((resolve, reject) => {
if (typeof money !== ‘number’) {
reject(new Error(‘money is not a number’))
} else {
resolve(money)
}
})
}
getMoneyBack(1200).then((money) => {
console.log(money)
})
What is a closure-
A closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function.
JavaScript, closures are created every time a function is created, at function creation time.
Closure Example :
function OuterFunction()
{
var outerVariable = 100;
function InnerFunction() {
alert(outerVariable);
}
return InnerFunction;
}
var innerFunc = OuterFunction();
innerFunc(); // 100