Skip to content
Related Articles

Related Articles

Reject Vs Throw Promises in JavaScript
  • Difficulty Level : Basic
  • Last Updated : 15 Apr, 2020

This article covers the use of reject and throw premises in Javascript and explains it’s differences.

reject(): It is an inbuilt function in Javascript that returns a Promise object which has been rejected for a particular given reason.

Syntax:

Promise.reject(reason)

Examples: The reason can be a simple string message or you can even pass an Error object.

  • Program 1: Passing a string message as the reason.




    <script>
    const p = new Promise( ( resolve, reject ) => { 
      
       reject( 'promise failed!' );
      
    });
    p.catch(err => { 
      
        console.log( err );
      
    });
    </script>
  • Output:
    promise failed!
  • Program 2: Passing an instanceOf Error as reason.




    <script>
    const p = new Promise( ( resolve, reject ) => { 
      
       reject( new Error( 'promise failed!' ) );
      
    });
    p.catch( err => { 
      
        console.log( err );
      
    });
    </script>
  • Output: As you can see when we are passing an Error object we get the entire Error tree. So it is upto the user which one the user prefers.
    Error: promise failed!
        at :4:9
        at new Promise ()
        at :2:11
        at render (tryit.php:202)
        at tryit.php:170
        at dispatch (jquery.js:4435)
        at r.handle (jquery.js:4121)

throw: It is used in JavaScript to create and throw user defined exceptions. Using JavaScript throw statement, you can completely control program flow and generate the user define error messages. If we use throw instead of reject() in the above two examples the results will be exactly same (you can try it yourself just by replacing reject with throw).



Examples: However throw can be used in any Javascript try-catch block and not only with promises.

  • Program 1: Using throw in a promise.




    <script>
    const p = new Promise( ( resolve, reject ) => { 
      
       throw( 'promise failed!' );
      
    });
    p.catch(err => { 
      
        console.log( err );
      
    });
    </script>
  • Output:
    promise failed!
  • Program 2: Using throw without a promise.




    <script>
    var a = 20;
    try
    {
      if( a < 25 )
      
        throw ( 'Less than 25' ); 
      
      console.log( 'Okay!' );
    }
    catch(err)
    {
      console.log( err );
    }
    </script>
  • Output: Now as we have understood the basic working of both reject and throw, let us talk about the differences between them:
    Less than 25

Comparison between Promise- reject and throw:

1. If there is an asynchronus callback function inside the Promise then we cannot use throw from inside the callback function as it will not be recognised by catch() and we will be getting an error in the output.

  • Program 1:




    <script>
    const p = new Promise( ( resolve, reject ) => {
          
        // Asynchronous function called within the Promise.
        setTimeout( () => {  
          throw( 'promise failed!' );
            
        }, 1000);
      });
      
      // The catch block will not be able to recognize the 
      // error thrown. It will become an uncaught exception.
      p.catch( ( err )=> {
      
        console.log( err ); 
      });
    </script>
  • Output: As you can see the error message (“promise failed!”) has been printed in the output but it wasn’t printed by the catch() function of our promise. It becomes an uncaught exception.
    /home/akarshan/Desktop/Projects/Personal/gfg/app.js:3
          throw( 'promise failed!' );
          ^
    promise failed!
    (Use `node --trace-uncaught ...` to show where the exception was thrown)
  • Program 2: To resolve the above situation we can make use of reject() method.




    <script>
    const p = new Promise( ( resolve, reject ) => {
      
        // Asynchronus function called within the Promise.
        setTimeout( () => { 
      
          reject( 'promise failed!' );
            
        }, 1000);
      });
      
      // The catch block will be able to recognize
      // the rejected statement.
      p.catch( (err) => {
      
        console.log( err ); 
      });
    </script>
  • Output: Here the catch block is able to recognise reject() and print the corresponding message.
    promise failed!

2. This is a very basic difference. If throw is encountered anywhere inside a function the exception is thrown immidiately and the control flow is terminated.In other words after throwing the exception control comes out of the function inside which the exception was thrown.

  • Program 1:




    <script>
    const p = new Promise( ( resolve, reject ) => {
      
      
          throw( 'promise failed!' );      
      
          console.log("Here");
      });
      
    p.catch( err => {
        console.log( err )
    });
    </script>
  • Output: From this example it is clear that the statement console.log(“Here”) is not getting executed.
    'promise failed!'
  • Program 2: To resolve above situation we use reject() instead of throw the statements after the reject statement inside the function will get executed before the control goes to the catch block.




    <script>
    const p = new Promise( ( resolve, reject ) => {
      
          reject( 'promise failed!' );      
      
          console.log( "Here" );
      });
      
    p.catch( err => {
      
        console.log( err )
    });
    </script>
  • Output:
    Here
    promise failed!

3. The reject can only be used with a Javascript promise but throw unlike reject can be used to create and throw user-defined exceptions in any try-catch block and not only the ones with promises. If you use Promise.reject() in a try-catch block which is not associated with a promise, UnhandledPromiseRejectionWarning error will pop up.

  • Program 1:




    <script>
    var a=20;
      
    try{
      
    if( a < 25 )
        
       Promise.reject ( 'Less than 25' );
      
    console.log( 'Okay!' );
    }
    catch(err)
    {
      console.log( "inside catch" );
      
      console.log( err );
    }
    </script>
  • Output: Here, UnhandledPromiseRejectionWarning error comes as Promise.reject() cannot find a catch block associated with a Promise object.
    Okay!
  • Program 2: The catch block in the above code is not associated with any Promise object and so it is not executed. This is clear from the output as the message “inside catch” is not getting printed. But if we use throw this error will not occur.




    <script>
    var a=20;
      
    try{
      
    if( a < 25 )
      
      throw ( 'Less than 25' );
      
    console.log( 'Okay!' );
      
    }
    catch(err)
    {
      console.log( "inside catch" );
      
      console.log( err );
    }
    </script>
  • Output:
    inside catch
    Less than 25

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :