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
Updated on: 2020-09-18T09:25:16+05:30

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements