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

Understanding Promise Resolution and Rejection

When creating promises, we use the Promise constructor which takes an executor function with two parameters: resolve and reject. The resolve function is called when the operation succeeds, while reject is called when it fails.

Example

Following is the code that demonstrates promise resolution and rejection based on a condition:

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);
})
success
failure

How It Works

The function expectedSumToBe creates a new Promise that simulates an asynchronous operation using setTimeout. After 3 seconds, it checks if the sum of the first two parameters equals the third parameter. If true, it resolves with 'success', otherwise it rejects with 'failure'.

Enhanced Example with Error Objects

For better error handling, we can reject with Error objects instead of strings:

const simulateApiCall = (a, b, expected) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const sum = a + b;
            if(sum === expected){
                resolve({ success: true, result: sum });
            } else {
                reject(new Error(`Expected ${expected} but got ${sum}`));
            }
        }, 1000);
    });
};

// Success case
simulateApiCall(10, 20, 30).then(data => {
    console.log('Success:', data);
}).catch(error => {
    console.log('Error:', error.message);
});

// Failure case  
simulateApiCall(10, 20, 25).then(data => {
    console.log('Success:', data);
}).catch(error => {
    console.log('Error:', error.message);
});
Success: { success: true, result: 30 }
Error: Expected 25 but got 30

Key Points

  • Use resolve() to indicate successful completion of the promise
  • Use reject() to indicate failure or error conditions
  • Handle resolved promises with .then()
  • Handle rejected promises with .catch()
  • Consider using Error objects for more informative error handling

Conclusion

Promises provide a clean way to handle asynchronous operations. By properly using resolve() and reject(), you can create robust functions that handle both success and failure scenarios effectively.

Updated on: 2026-03-15T23:18:59+05:30

165 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements