Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How does Promise.any() method differs from Promise.race() method in JavaScript ?
Next article icon

Promise reject does not propagate the error correctly in JavaScript

Last Updated : 29 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will try to understand why Promise's reject() method doesn't propagate the error correctly, and later we will see the solution for the same along with certain theoretical explanations and coding examples.

Let us first have a look into the following section quickly which enlightens us on the syntax of how a promise will be created.

Syntax: Following syntax, we may use in order to create a new promise which will either resolve or reject as per the need:

let promise_variable_name = new Promise ((resolve, reject) => {     // Do something...     // Either resolve it with certain parameters     // inside resolve() method or either reject it     // with reject statement in reject() method });

Now we will have a look over the following shown syntax of then() as well as the catch() method which we will use to execute/catch an error received from the previously created promise:

promise_variable_name.then((result) => {     // Do something with result parameter's value })  // Further catch statement has to be added // in case of any error caught .catch((error) => {     // Do something with this error variable })

Now that we have seen all the syntaxes and analyzed them carefully let's see a quick example that will help us to understand all in a very better and more efficient manner.

Example: In this example, we will create a promise using the above-shown syntax and execute them in order to display the result correctly over the console.

JavaScript
<script>     let promise = new Promise((resolve, reject) => {         resolve("This article is available on "             + "the GeeksforGeeks platform...");     });      promise         .then((result) => console.log(result))         .catch((error) => console.log(error)); </script> 

Output:

This article is available on the GeeksforGeeks platform...

Now that we have seen the promise's execution using the above example. Let's have a look over the following examples in which we will try to analyze our problem statement as well as its solution.

Example 1: 

  • In this example, we will create a function that will accept a number (either positive or negative), and then we will create a promise through the above-shown syntax. 
  • Then inside that promise, we will apply a condition (with the help of an if-statement) which will check the number's value as per the requirement. 
  • Then if that number matches the requirement, we will apply the reject() method that will contain a certain statement in itself. Afterward, we have added a line that is not required as an output on the console side but still, we have added it in order to see if and not our code works fine or not. 
  • Then at last we will call our method using both the then() method (for printing result) and catch() method (in order to catch the error caught, if so).
JavaScript
<script>     let checkNumValue = (num) => {         return new Promise((resolve, reject) => {             if (num === 0) {                 console.log("Zero number received...!!");                 reject("Stop code's execution since "                     + "invalid number caught...");             }             console.log("This line is of no use, hence "                 + "not required in output...!!!");         });     };      checkNumValue(0)         .then((result) => console.log(result))         .catch((error) => console.log("Caught Error: " + error)); </script> 

Output:

Zero number received...!! This line is of no use, hence not required in output...!!! Caught Error: Stop code's execution since invalid number caught...

Now as we have seen that one unwanted line gets printed in the browser's console which was not required here and the reason for the same is that when the reject() method is called, it will do the work and make the control flow goes on and it would stop it's execution until something explicitly passed in after reject() method execution statement.

Example 2: 

  • In this example, we will take into consideration the previous example's code and further, we will add certain changes in the function itself to make it executable as per the need. 
  • In this method after the reject() function call, we will add an empty return statement which will make the execution end or completed over that point itself and will not move further. 
  • With this return statement that one extra line gets omitted and will not be displayed over the browser's console as an output.
JavaScript
<script>     let checkNumValue = (num) => {         return new Promise((resolve, reject) => {             if (num === 0) {                 console.log("Zero number received...!!");                 reject("Stop code's execution since "                     + "invalid number caught...");                 return; // This line marks end of execution             }             console.log("This line is of no use, hence "                 + "not required in output...!!!");         });     };      checkNumValue(0)         .then((result) => console.log(result))         .catch((error) => console.log("Caught Error: " + error)); </script> 

Output:

Zero number received...!! Caught Error: Stop code's execution since invalid number caught...

Next Article
How does Promise.any() method differs from Promise.race() method in JavaScript ?
author
amansingla
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions
  • JavaScript-Statements

Similar Reads

  • How to create a global Promise Rejection Handler in JavaScript ?
    In this article, we will try to understand firstly how we create a Rejected Promise, and later we will see how we may create a Global Promise Rejection Handler which will try to handle (somehow) that Rejected Promise created earlier in JavaScript. Let us first try to understand how we create a Promi
    2 min read
  • JavaScript Promise constructor Property
    JavaScript Promise constructor property is used to return the Promise constructor function for the object. The function which is returned by this property is just a reference to this function, not a Promise containing the function's name. The JavaScript number constructor, string constructor, and bo
    1 min read
  • How to access the Value of a Promise in JavaScript
    In this article, we will see how to access the value of Promise in JavaScript. The Promise is a feature of ES6 introduced in 2015. The concept of Promises is generally used when we want to work asynchronously. The value of a Promise can be accessed in JavaScript using the following methods. Table of
    2 min read
  • How does Promise.any() method differs from Promise.race() method in JavaScript ?
    In this article, we will first try to understand how we may declare or use Promise.any() and Promise.race() methods followed by some facts which will eventually help us to understand how they differ from each other (through theoretical as well as coding examples). Let us first quickly understand in
    5 min read
  • JavaScript Error Object Complete Reference
    Error objects are arising at runtime errors. The error object also uses as the base object for the exceptions defined by the user. The complete list of JavaScript Error Object properties are listed below: Error types JavaScript RangeError – Invalid dateJavaScript RangeError – Repeat count must be no
    3 min read
  • Throwing an Error "cannot read property style of null" in JavaScript
    In this article, we will see how we may receive an error "cannot read property style of null" in JavaScript, along with understanding the cause to get this error with the help of an example, and thereafter we will try to understand how we may correct it with certain small changes in the code snippet
    3 min read
  • How to run a given array of promises in series in JavaScript ?
    Given an array of Promises, we have to run that in a series. To do this task, we can use then(), to run the next promise, after the completion of a promise. Approach: The then() method returns a Promise, which helps us to chain promises/methods. The Promise.resolve() method executes the first callba
    3 min read
  • Why Promise.all doesn't reject when a non-promise throws an error ?
    In this article, we will talk about why Promise.all() method does not get rejected when one of the non-input promises throws an error, and in which cases the Promise.all() does get rejected. Promise.all() is a method that returns a promise. It takes an array of promises as its argument and returns a
    3 min read
  • Reject Vs Throw Promises in JavaScript
    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 sim
    5 min read
  • How to call promise inside another promise in JavaScript ?
    In JavaScript, to call promise inside another promise we first declare a promise using its basic syntax and further execute this promise then create another which is to be called inside the previous promise for its execution. Promise is basically a JavaScript object which is responsible for handling
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences