Javascript - Handling reject in a Promise
Rishad Omar

Rishad Omar @rishadomar

About: Enjoy coding. Currently building Flutter, React and backend NodeJS apps.

Location:
Cape Town
Joined:
Aug 26, 2019

Javascript - Handling reject in a Promise

Publish Date: Nov 1 '23
0 2

To demonstrate that reject does not halt processing I wrote this trivial example.

function wait(seconds) {
    return new Promise((resolve, reject) => {
        if (seconds == null || seconds == 5) {
            console.log('Before reject');
            reject('Please supply number not equal to 5');
            console.log('After reject');
        }
        setTimeout(() => {
            resolve('Done');
        }, seconds * 1000);
    });
}
Enter fullscreen mode Exit fullscreen mode

It's a function that returns a Promise.
If the seconds specified is 5, then the expected behavior is to reject and not wait.
Any other value, I expect it to wait the specified time.

This is how I call my function:

wait(seconds)
    .then(() => {
        console.log('Successfully completed test');
    })
    .catch((error) => {
        console.error('Error in test', error);
    });
Enter fullscreen mode Exit fullscreen mode

Here is my output when running the function:

Test 1

With a value of seconds = 7
The wait function behaves as expected. It waits 7 seconds and resolves.

Successfully completed test
Enter fullscreen mode Exit fullscreen mode

Test 2

With a value of seconds = 5
The wait function does not behave as expected. It waited 5 seconds!

Before reject
After reject
Error in test Please supply number not equal to 5
Enter fullscreen mode Exit fullscreen mode

I didn't expect the "After reject" and I didn't expect it to wait the 5 seconds.
To correct this add a return statement after the reject.

function wait(seconds) {
    return new Promise((resolve, reject) => {
        if (seconds == null || seconds == 5) {
            reject('Please supply number not equal to 5');
            return; // Do not continue
        }
        setTimeout(() => {
            resolve('Done');
        }, seconds * 1000);
    });
}
Enter fullscreen mode Exit fullscreen mode

Now re-executing test 2 above produces:

Error in test Please supply number not equal to 5
Enter fullscreen mode Exit fullscreen mode

And there was no wait which is the expected behavior.

Read more about Promises here: https://www.freecodecamp.org/news/javascript-es6-promises-for-beginners-resolve-reject-and-chaining-explained/

Comments 2 total

  • Rishad Omar
    Rishad OmarNov 1, 2023

    An alternative to using the return is to use an else.

    function wait(seconds) {
        return new Promise((resolve, reject) => {
            if (seconds == null || seconds == 5) {
                reject('Please supply number not equal to 5');
            } else {
                setTimeout(() => {
                    resolve('Done');
                }, seconds * 1000);
            }
        });
    }
    
    Enter fullscreen mode Exit fullscreen mode
    • Barry Michael Doyle
      Barry Michael DoyleNov 1, 2023

      In my opinion the else approach is a bit messy vs early return. And early return is a nice way to act as a guard statement that doesn't nest the code an extra layer like the else statement does.

      You could (and probably should) just return the reject statement like this:

      function wait(seconds) {
        return new Promise((resolve, reject) => {
          if (seconds == null || seconds == 5) {
            return reject('Please supply number not equal to 5');
          }
          setTimeout(() => {
            resolve('Done');
          }, seconds * 1000);
        });
      }
      
      Enter fullscreen mode Exit fullscreen mode
Add comment