Introduction to Promises
Way Promises work
Creating Promises
const printSomething = (isValid) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (isValid) {
console.log('Yes I am valid');
resolve();
} else {
console.log('Sorry I am invalid');
}
}, 1000);
});
}
Promise provides resolve and reject to return values to the calling function in case of success or error respectively.
Consuming Promises
const printSomething = (isValid) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (isValid) {
console.log('Yes I am valid');
resolve();
} else {
console.log('Sorry I am invalid');
}
}, 1000);
});
}
printSomething(true)
.then(() => printSomething(true))
.then(() => printSomething(false));
Here is the outcome -
Yes I am valid
Yes I am valid
Sorry I am invalid
You can execute the code here.
Chaining Promises
const printSomething = (name, textToAdd) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
var retValue = '';
if (name != null) {
retValue = name + ' ' + textToAdd;
} else {
retValue = textToAdd;
}
console.log(retValue);
resolve(retValue);
}, 1000);
});
}
printSomething(null, 'Hello')
.then((result) => printSomething(result, 'Sudipta'))
.then((result) => printSomething(result, 'Deb'));
Here is the result
Hello
Hello Sudipta
Hello Sudipta Deb
You can execute the code here.
Handling Errors
const printSomething = (name, textToAdd) => {
return new Promise((resolve, reject) => {
try {
setTimeout(() => {
if (textToAdd == null) {
reject(new Error('textToAdd can not be null'));
} else {
var retValue = '';
if (name != null) {
retValue = name + ' ' + textToAdd;
} else {
retValue = textToAdd;
}
console.log(retValue);
resolve(retValue);
}
}, 1000);
} catch (e) {
reject(e);
}
});
}
printSomething(null, 'Hello')
.then((result) => printSomething(result, 'Sudipta'))
.then((result) => printSomething(result, 'Deb'))
.then((result) => printSomething(result, null))
.then((result) => printSomething(result, 'From Canada'))
.catch(err => console.log('Error occured: ' + err.message));
Hello
Hello Sudipta
Hello Sudipta Deb
Error occured: textToAdd can not be null
You can execute the code here.
Now let's modify the same example, where instead of returning Reject promise, I will throw the error. This is helpful to handle runtime error.
const printSomething = (name, textToAdd) => {
return new Promise((resolve, reject) => {
try {
setTimeout(() => {
if (textToAdd == null) {
throw "textToAdd can not be null";
} else {
var retValue = '';
if (name != null) {
retValue = name + ' ' + textToAdd;
} else {
retValue = textToAdd;
}
console.log(retValue);
resolve(retValue);
}
}, 1000);
} catch (e) {
reject(e);
}
});
}
printSomething(null, 'Hello')
.then((result) => printSomething(result, 'Sudipta'))
.then((result) => printSomething(result, 'Deb'))
.then((result) => printSomething(result, null))
.then((result) => printSomething(result, 'From Canada'))
.catch(err => console.log('Error occured: ' + err.message));
One important fact is that reject DOES NOT terminate control flow like a return statement does. In contrast throw does terminate control flow.
Let's have the below code with reject
const printSomething = (name, textToAdd) => {
return new Promise((resolve, reject) => {
try {
setTimeout(() => {
if (textToAdd == null) {
reject(new Error('textToAdd can not be null'));
} else {
var retValue = '';
if (name != null) {
retValue = name + ' ' + textToAdd;
} else {
retValue = textToAdd;
}
console.log(retValue);
resolve(retValue);
}
}, 1000);
} catch (e) {
reject(e);
}
});
}
printSomething(null, 'Hello')
.then((result) => printSomething(result, 'Sudipta'))
.then((result) => printSomething(result, 'Deb'))
.then((result) => printSomething(result, null))
.then((result) => printSomething(result, 'From Canada'))
.catch(err => console.log('Error occured: ' + err.message))
.then(() => console.log('I will still execute even after the error'));
Output:
"Hello"
"Hello Sudipta"
"Hello Sudipta Deb"
"Error occured: textToAdd can not be null"
"I will still execute even after the error"
You can execute the code here. Here you can see that catch and then statement are getting executed even after reject promise return.
Now let's have the same code with throw statement
const printSomething = (name, textToAdd) => {
return new Promise((resolve, reject) => {
try {
setTimeout(() => {
if (textToAdd == null) {
throw "textToAdd can not be null";
} else {
var retValue = '';
if (name != null) {
retValue = name + ' ' + textToAdd;
} else {
retValue = textToAdd;
}
console.log(retValue);
resolve(retValue);
}
}, 1000);
} catch (e) {
reject(e);
}
});
}
printSomething(null, 'Hello')
.then((result) => printSomething(result, 'Sudipta'))
.then((result) => printSomething(result, 'Deb'))
.then((result) => printSomething(result, null))
.then((result) => printSomething(result, 'From Canada'))
.catch(err => console.log('Error occured: ' + err.message))
.then(() => console.log('I will still execute even after the error'));
Output:
"Hello"
"Hello Sudipta"
"Hello Sudipta Deb"
"Uncaught textToAdd can not be null (line 6)"
You can execute the code here. You see this time the catch and then statements are not getting executed. The reason is that throw statement terminate the control flow.
Promise.all()
var returnDouble = (value) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (value > 0) {
resolve(value * 2);
} else {
reject(resolve);
}
}, 1000);
});
};
var promisesToMake = [returnDouble(20), returnDouble(10), returnDouble(5)];
var finalPromise = Promise.all(promisesToMake);
finalPromise.then(function (results) {
console.log('Final Result: ' + results);
});
Now let's forcefully reject one promise in the below example -
var returnDouble = (value) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (value > 0) {
resolve(value * 2);
} else {
reject(resolve);
}
}, 1000);
});
};
var promisesToMake = [returnDouble(20), returnDouble(0), returnDouble(5)];
var finalPromise = Promise.all(promisesToMake);
finalPromise
.then((results) => console.log('Final Result: ' + results))
.catch(err => console.log('Error occured'));
Output:
"Error occured"
You can execute the code here. In this example, the second call is failed, even though the first and third call is successful. But still the final result is failure.
Promise.race()
var returnDouble = (value,time) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (value > 0) {
resolve(value * 2);
} else {
reject(resolve);
}
}, time);
});
};
var promisesToMake = [returnDouble(20,100), returnDouble(200,50), returnDouble(5,500)];
var finalPromise = Promise.race(promisesToMake);
finalPromise
.then((results) => console.log('Final Result: ' + results))
.catch(err => console.log('Error occured'));
"Final Result: 400"





very nice post thankyou for sharing.
Sobha Royal Pavilion Sarjapur Road
great Info.
thank for the info.
keep sharing
nice information
best Deep Learning Training course in Bangalore
python certification training course in Bangalore
Thanks for sharing useful information.
web designing course with placement
Greetings! Very helpful advice within this article! It’s the little changes that produce the biggest changes. Thanks for sharing!