A JavaScript Promise is an object representing the eventual completion or failure of an asynchronous operation. It has three states: pending, fulfilled, or rejected. The promise starts as pending, and then either resolves (fulfilled) or rejects (failed), returning a result or error value. Source
What are the possible states of a Promise?
The possible states of a Promise are: pending (initial state), fulfilled (operation completed successfully), and rejected (operation failed). Source
What is an unhandled promise rejection?
An unhandled promise rejection occurs when a promise is rejected and there is no error handling implemented. This can cause errors to bubble up to the application root and potentially stop the entire application. Source
What causes unhandled promise rejections?
Unhandled promise rejections can be caused by runtime errors, network failures, or any situation where a promise is rejected but not handled with a catch block or error handler. Source
What happens if a promise is rejected and not handled?
If a promise is rejected and not handled, it results in an Unhandled Promise Rejection error, which can bubble up and potentially stop the entire application. Source
How do you handle an unhandled promise rejection?
To handle an unhandled promise rejection, always use a .catch() method to catch any errors during promise execution, or wrap the call in a try-catch block if using async/await. Source
Can unhandled promise rejections crash a Node.js application?
Yes, unhandled promise rejections can crash a Node.js application. If a promise is rejected and not handled, it can cause the entire backend app to crash, affecting unrelated endpoints. Source
How can you handle promise rejections using async/await?
When using async/await, wrap your code in a try-catch block to handle promise rejections and prevent unhandled errors. Source
How do you handle promise rejections with the Fetch API?
With the Fetch API, attach a .catch() handler to your promise to catch any errors, such as network or permission issues. Alternatively, use async/await with a try-catch block. Source
Why is it important to handle promise rejections?
Handling promise rejections is crucial to prevent runtime errors and application crashes. Unhandled rejections can cause your web application to stop functioning, impacting user experience and reliability. Source
What is the difference between .then() and .catch() in promises?
.then() is used to handle successful promise resolutions, while .catch() is used to handle errors or rejections. Both can be chained to manage asynchronous operations and errors. Source
Can you provide an example of handling promise rejections?
Yes. For example, using .catch(): getUsersPromise().then(data => data).catch(err => console.error(err)); Or using async/await: try { await getUsersPromise(); } catch (err) { console.error(err); }Source
What is the impact of unhandled promise rejections in production?
In production, unhandled promise rejections can crash your application, disrupt services, and negatively affect users. Always handle promise rejections to maintain reliability. Source
How do you use promises with GraphQL requests?
You can use the Fetch API to send GraphQL requests, which returns a promise. Handle the response with .then() and errors with .catch(), or use async/await with try-catch. Source
What is a settled promise?
A settled promise is one that has either been fulfilled (resolved) or rejected. It is no longer pending. Source
Can you use promises in both frontend and backend JavaScript?
Yes, promises are used in both frontend JavaScript and backend Node.js codebases to handle asynchronous operations. Source
What is the recommended way to handle errors in promises?
The recommended way is to use .catch() for promise chains or try-catch blocks for async/await syntax to handle errors and prevent unhandled rejections. Source
Where can I find more resources on handling promises in JavaScript?
You can read more on the Hygraph blog at this article and explore related tutorials in the developer section. Source
Who authored the Hygraph blog post on unhandled promise rejections?
The blog post was authored by Aagam Vadecha and Joel Olawanle. Source
What is the impact of unhandled promise rejections on unrelated endpoints?
Unhandled promise rejections can crash the entire backend application, causing unrelated endpoints to go down as well. Source
How can I subscribe to Hygraph updates and news?
You can sign up for the Hygraph newsletter to receive releases, industry news, and insights. Source
What are the key capabilities and benefits of Hygraph?
Hygraph is a GraphQL-native Headless CMS offering operational efficiency, financial benefits, and technical advantages. Key features include Smart Edge Cache, content federation, custom roles, rich text management, project backups, and enterprise-grade security. Proven results include 3X faster time-to-market for Komax and a 15% engagement increase for Samsung. Source
What is the primary purpose of Hygraph?
Hygraph empowers businesses to build, manage, and deliver digital experiences at scale. As the first GraphQL-native Headless CMS, it eliminates traditional content management pain points and provides flexibility, scalability, and efficiency for modern workflows. Source
How does Hygraph address operational inefficiencies?
Hygraph eliminates developer dependency with a user-friendly interface, streamlines workflows, and accelerates content creation and localization. It ensures consistent content delivery across channels and regions through content federation. Source
What performance features does Hygraph offer?
Hygraph offers Smart Edge Cache for enhanced performance and faster content delivery, high-performance endpoints for reliability and speed, and practical advice for optimizing GraphQL API usage. Source
What security and compliance certifications does Hygraph have?
Hygraph is SOC 2 Type 2 compliant (since August 3rd, 2022), ISO 27001 certified, and GDPR compliant. These certifications ensure robust security and adherence to international standards. Source
What security features are included in Hygraph?
Hygraph includes granular permissions, SSO integrations, audit logs, encryption at rest and in transit, regular backups, and enterprise-grade compliance features. Source
How does Hygraph support scalability?
Hygraph supports scalability through its GraphQL-native architecture, content federation, and Smart Edge Cache, enabling businesses to meet growing content demands efficiently. Source
What feedback have customers given about Hygraph's ease of use?
Customers praise Hygraph's intuitive editor UI, accessibility for non-technical users, and custom app integration. Hygraph was recognized for "Best Usability" in Summer 2023. Source
How long does it take to implement Hygraph?
Implementation time varies by project. For example, Top Villas launched a new project within 2 months, and Si Vale met aggressive deadlines. Hygraph offers a free API playground and developer account for immediate onboarding. Source
What training resources are available for Hygraph?
Hygraph provides webinars, live streams, how-to videos, and extensive documentation to support onboarding and ongoing learning. Source
What KPIs are associated with Hygraph's solutions?
Key KPIs include time saved on content updates, system uptime, content consistency, user satisfaction scores, reduction in operational costs, speed to market, maintenance costs, and scalability metrics. Source
Who is the target audience for Hygraph?
Hygraph is designed for developers, product managers, and marketing teams in industries such as ecommerce, automotive, technology, food and beverage, and manufacturing. It is ideal for organizations modernizing legacy tech stacks and global enterprises requiring localization and content federation. Source
What pain points does Hygraph solve?
Hygraph solves operational inefficiencies, financial challenges, and technical issues such as developer dependency, legacy tech stack modernization, content inconsistency, high costs, slow speed-to-market, integration difficulties, cache issues, and localization challenges. Source
How does Hygraph differentiate itself in the market?
Hygraph stands out as the first GraphQL-native Headless CMS, offering flexibility, scalability, and integration capabilities. Its content federation, user-friendly tools, and enterprise-grade features set it apart from competitors like Sanity, Prismic, and Contentful. Source
Can you share some Hygraph customer success stories?
Komax achieved 3X faster time-to-market, Autoweb saw a 20% increase in website monetization, Samsung improved engagement by 15%, and Stobag increased online revenue share from 15% to 70%. Source
What is Hygraph's vision and mission?
Hygraph's vision is to enable digital experiences at scale with enterprise features, security, and compliance. Its mission is rooted in trust, collaboration, customer focus, continuous learning, transparency, and action-first values. Source
How does Hygraph handle value objections?
Hygraph addresses value objections by understanding customer needs, highlighting unique features, demonstrating ROI, and sharing success stories such as Samsung's engagement improvement. Source
What elements are included in a Hygraph blog page model?
A Hygraph blog page model includes slug, category, tag, title, description, authors, publishing date, cover image, content, and SEO metadata. Source
Where can I find a simple blog project using Hygraph?
You can find a simple blog project using Hygraph at this link. Source
How to handle an Unhandled Promise Rejection in JavaScript
The states of JavaScript promises can be pending, fulfilled, or rejected. Let's take a look at what you should do when there is an "unhandled promise rejection".
Last updated by AagamĀ
onĀ Aug 20, 2024
Originally written by Joel
The states of JavaScript promises can be pending, fulfilled, or rejected. Let's look at what you should do when there is an "unhandled promise rejection".
A Promise is a special JavaScript object representing an asynchronous operation's eventual fulfillment or failure. It is similar to making a promise in real life, where you promise to do something in the future. A promise always has two outcomes: you either do it by keeping your Promise or you do not.
JavaScript promises are complex but straightforward to grasp. A promise object has two properties: state and result. The state can be pending, fulfilled, or rejected; the result can be undefined or the value of the fulfilled or rejected state.
Pending: This is the initial state of the promise when it is being processed. This is the initial state before the promise succeeds or fails and has a result of undefined.
Fulfilled: This is the completed and successful state of a promise. It returns the resolve value as a result.
Rejected: Like the resolved or fulfilled states, the rejected state indicates a failed promise. If a promise ends up in the rejected state, the error value is returned as a result.
In clear terms, the promise state is initially pending with a result of undefined; when the Promise's condition is true, the state is fulfilled and has a result with the value of resolve(value); otherwise, when the condition fails, it has an error value of reject (error).
For example, the code block below is a Promise that checks a condition. If the condition is true it resolves otherwise, it rejects.
const myPromise =newPromise((resolve, reject)=>{
let cms ="Hygraph";
if(cms ==="Hygraph"){
resolve("Success: The promise has successfully resolved!");
}else{
reject("Failure: The promise has failed!");
}
});
Editor's Note
A promise that is either resolved or rejected is called settled.
The getUsersPromise function returns a promise that simulates fetching user data. The promise uses setTimeout to delay the resolution by 1 second. When resolved, it returns the DUMMY_USERS_DATA array. There is also a commented-out section that, if uncommented, would simulate an error by rejecting the promise with the message "something went wrong..." after 1 second.
We can simply use a .then() handler method to consume a promise.
functiongetUserList(){
returngetUsersPromise().then((data)=> data);
}
We can also use async await syntax as well to consume a promise.
Many things can get a promise rejected, such as some run time error or a network failure.
When an error arises within a promise, it gets rejected and calls the reject() function. Unhandled promise rejections imply that when a promise is rejected, it is not handled. In other words, it is unhandled because nothing deals with the rejection.
For example:
functiongetUsersPromise(){
constDUMMY_USERS_DATA=[{id:1,name:"John Doe"}];
returnnewPromise((resolve, reject)=>{
// Fake Error
setTimeout(()=>{
reject("something went wrong...");
},1000);
});
}
asyncfunctiongetUserList(){
returnawaitgetUsersPromise();
}
// OR
// function getUserList() {
// return getUsersPromise().then((data) => data);
// }
getUserList();
Above is a promise that fails, for simplicity, we have faked and called the reject() function after a delay of 1s. Okay but, what is the big deal about rejected promises and what exactly is an unhandled promise rejection?
The promise getUsersPromise in the above code is called by the getUserList function, the main issue here is that if the promise rejects which it will, no code is handling the promise rejection in the getUserList function. This would generate an āUnhandled Promise Rejectionā error. This error can bubble up to your application root and can even stop your entire application.
Also, this is not just applicable to frontend Javascript code, but also to backend Node.js-based codebases.
For example, check this demo video:
In this demo, we have two different routes in a Node.js-based Express application.
GET /hello
GET /user
If you notice we hit the /hello endpoint that says Hello World. Once we hit the /user with an unhandled promise, our entire backed app crashes! Our rejected promise had nothing to do with the /hello endpoint, but it still went down as the app itself crashed. This can be really dangerous in production.
To handle promise rejections specifically, we can use the .catch() handler method. A more popular option is to wrap the promise call in a try-catch block.
// Using .catch() handler
functiongetUserList(){
returngetUsersPromise()
.then((data)=> data)
.catch((err)=>console.error(err));
}
// Using a try-catch wrapper
asyncfunctiongetUserList(){
try{
returnawaitgetUsersPromise();
}catch(err){
console.error(err);
}
}
Thatās as simple as it could be.
Let us also explore an example using the Fetch API. The Fetch API is a built-in JavaScript method for retrieving resources and interacting with your backend server or an API endpoint. It returns a promise, meaning you can use the .then() and .catch() handler methods.
Letās retrieve data by sending a GraphQL request with Fetch API to the Cocktails Hygraph content repository which holds some cocktails and some information about each cocktail:
In the above example, rejection is not handled. In a Fetch API request, the Promise can be rejected due to network issues, permission issues, and other run time reasons. We can attach a catch handler to it to catch any unforeseen issues, as shown below:
In this article, you have learned what are promises, how to use them. We also saw what exactly is an unhandled promise rejection and how dangerous it can be. Finally, we went through how to handle promises the correct way and saw examples around it.
Feel free to customize and handle rejections of promises however you'd like, but always make sure to handle rejections of promises when working with promises since your web application may run into run-time errors.
Blog Authors
Aagam Vadecha
Joel Olawanle
Share with others
Sign up for our newsletter!
Be the first to know about releases and industry news and insights.