Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Resolving or rejecting promises accordingly - JavaScript
We are required to write a JavaScript function that imitates a network request, for that we can use the JavaScript setTimeout() function, that executes a task after a given time interval.
Our function should return a promise that resolves when the request takes place successfully, otherwise it rejects
Example
Following is the code −
const num1 = 45, num2 = 48;
const res = 93;
const expectedSumToBe = (num1, num2, res) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if(num1 + num2 === res){
resolve('success');
}else{
reject('failure');
};
}, 3000);
});
};
expectedSumToBe(num1, num2, res).then((data) => {
console.log(data);
}).catch((err) => {
console.log(err);
})
expectedSumToBe(23, 56, 76).then((data) => {
console.log(data);
}).catch((err) => {
console.log(err);
})
Output
Following is the output in the console −
success failure
Advertisements