Resolving or rejecting promises accordingly - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Published on 18-Sep-2020 09:24:25
Advertisements