Capturing Mistakes in Promises Using Async/Await

I'm running into an issue where I need to handle errors within a promise using async/await, but the current code keeps resulting in an "Uncaught Error ..."

function makeMistake() {
    var promise = new Promise(function(resolve, reject){
        setTimeout(function() {
            throw new Error("Oops! An error occurred.");
            resolve('Hello from makeMistake function');
        }, 1000);
    });
    return promise;
}

async function waitForError() {
    try {
        await makeMistake();
    } catch(e) {
        console.log ('*****Successfully caught the error! *****');
    }
}

waitForError()

Answer №1

The error is being triggered within the setTimeout function, not from a promise callback. Since timer callbacks like this are asynchronous, any errors thrown will not be caught and will likely be displayed in the browser console.

To reject the promise you've created, make sure to use the reject method:

function troubleshoot() {
    var promise = new Promise(function(resolve, reject){
        setTimeout(function() {
            reject(new Error("Error thrown from troubleshoot()"));
            resolve('Greetings from troubleshoot function'); // This line serves no purpose now
        }, 1000);
    });
    return promise;
}

If you want to handle any synchronous errors inside the timer callback and pass them to reject, you can utilize try/catch:

function troubleshoot() {
    var promise = new Promise(function(resolve, reject){
        setTimeout(function() {
            try {
                throw new Error("Error thrown from troubleshoot()");
                resolve('Greetings from troubleshoot function'); // This line will never execute
            } catch (e) {
                reject(e);
            }
        }, 1000);
    });
    return promise;
}

Answer №2

When using a try-catch block in conjunction with the await keyword, it specifically checks for the promise to either be fulfilled or rejected.

If you reject the promise and throw an error that is not related to the resolution of the promise (as you are currently doing), then it will be caught by your existing setup.

It's important to note that the error being thrown currently has no connection to the asynchronous operation being executed.

function messup() {
    var promise = new Promise(function(resolve, reject){
        setTimeout(function() {
            reject("Thrown from messup()"); //<-- do this instead
        }, 1000);
    });
    return promise;
}

To delve deeper into this topic, check out my exploration of async/await error handling in this detailed guide on async/await.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Chai-http does not execute async functions on the server during testing

In my app.js file, there is a function that I am using: let memoryCache = require('./lib/memoryCache'); memoryCache.init().then(() => { console.log("Configuration loaded on app start", JSON.stringify(memoryCache.getCache())); }); app.use( ...

Error: Unable to access the 'wsname' property of an undefined value

I am attempting to retrieve values from a database using the code below (login.js) $.post("http://awebsite.com/app/login.php",{ rep1: rep, password1:password}, function(data) { if(data=='Invalid rep.......') { $('input[type="text"]').c ...

Tips for creating a POST request using mongoose in NextJS version 13.4

Currently, I am faced with the challenge of executing a POST request using mongoose in NextJS. In my project structure, I have three key files: lib/dbConnect.js, models/User.js, and app/new/route.ts. As defined, app/new/route.ts is responsible for handling ...

Generating dynamic forms using JSON Schema in Angular 8 can greatly streamline the form creation process

Struggling with generating dynamic forms from JSON Schema in Angular 8, I stumbled upon a couple of libraries. One seemed outdated with its last commit around 2 years ago, while the other appeared to be a more recent fork of it for Angular 8. The first li ...

Creating Sliding Panels: A Step-by-Step Guide

I am new to JavaScript and jQuery, and I am looking to create a panel system similar to Spotify's design. Here is a description of what I am trying to achieve: When a user clicks on an artist or song/album on Spotify, a panel slides in from the righ ...

Guide on creating a dynamic slideshow viewer

I'm interested in learning how to implement a sliding image viewer using javascript or jquery. Based on what I've observed, these viewers feature images aligned side by side with buttons that shift the images depending on their width to display t ...

Repeatedly utilizing a drop-down menu

Can a <select> menu be written and utilized in multiple locations on a webpage? For instance: <select id="dm"> <option value="">Select Quantity</option> <option value="less ">50 - 60</option> <option value="me ...

Tips for assigning a class name to a variable element within a react component?

I am interested in dynamically adding classes to an element. While I am familiar with methods using html-dom and passing a JavaScript expression to className, I am seeking a different approach. Is there a way to add classes similar to pushing them to an ar ...

The functionality of submitting an Ajax form is only successful on Firefox browser

My Ajax login form is functioning properly only on Firefox. However, in other browsers, it continues to submit the form and load the function page. I aim for it to send the two fields to a function page, validate them in the background, and display the res ...

When the AJAX function is called again, the previous loading process is interrupted, without the use of jQuery

I have created a function that loads a URL into an element, but it seems to be encountering issues when called repeatedly in a loop to load multiple elements. The current load operation stops prematurely: function loadDataFromURL(url, elementId) { var ...

Can someone explain the intention behind using the code snippet {...rest}? I already understand how the three dots spread notation works in React Javascript

I already understand what the three dots spread notation in React Javascript does, so no need to explain. I have been learning ReactJs Javascript and reading code, and I recently came across this CodeSandbox example Within the code, there is: https://i ...

Simultaneous appearance of multiple jQuery dialogs

As I work on creating a team page, each team member has their own div that contains a photo and employee information. My goal is to have a dialog box pop up when the photo is clicked, using the $this context to retrieve the employee data from the same div. ...

Encountering an error in Express while attempting to upload an image due to the inability to read the property 'file' of undefined

I am currently learning Express framework. I encountered an error while trying to upload an image using Express. The error message I received is "Cannot read property 'file' of undefined." Below are the code snippets that I am using, and I&apo ...

What is the best way to format the incoming data to display as HTML code?

My textarea has a v-model called content where input text is assigned to content.description. Now, I need to transfer this information to another element, specifically a div. The challenge lies in the fact that if my textarea includes HTML code, I want it ...

What could be causing the Babel installation to fail within Electron? Is Babel necessary for my project or can it be avoided?

Having trouble using the npm package https://www.npmjs.com/package/swipe-detect and encountering the following error message: export default function(target, callback, threshold=150) { ^^^^^^ SyntaxError: Unexpected token export at Module._compile (i ...

Strategies for resolving a mix of different data types within a single parameter

Here, I am setting up the options params to accept a value that can either be a single string or another object like options?: string[] | IServiceDetail[] | IServiceAccordion[]; However, when attempting to map these objects, an error is encountered: Prope ...

MongooseError: The operation `users.findOne()` has encountered an issue

While working on my movie website, I encountered an issue when setting up the login feature. When trying to register using POST through Insomnia, I received an error message stating "MongooseError: Operation users.findOne() buffering timed out after 10000m ...

Using the jQuery unbind method allows the function to execute only once, however, the event will not be

On my main page, I have a radio button that passes a value via Ajax when clicked. The result is then checked by Ajax and the corresponding output is displayed for each question as correct/incorrect. I am facing an issue with the unbind event - it works fin ...

stop harmful code written in javascript from running

Recently, I came across a troubling situation on my WordPress site. I discovered a malware script that automatically adds a malicious javascript tag whenever I attempt to save a page and click on the text panel in WYSIWYG editor. The unwanted script that k ...

Is it feasible to impersonate a session in PHP by manipulating cookies on the client-side with JavaScript?

Is it possible for an unauthorized visitor to view, delete, or edit session cookies in a PHP web app if HttpOnly cookies are not being used? What happens when a user on a non-session page of a web app sets a cookie with the same name as a session page coo ...