What is the best way to retrieve the promise that encountered an error in the catch block while using async/await

I'm currently in the process of converting code that used .then/.catch to instead use async/await. One particular challenge I'm facing is how to access the original promise that fails within the catch block, for logging purposes.

Here is the original code snippet:

const myPromise = somePromise()

myPromsise.then(() => {
    //...
}).catch((error) => {
    errorLogger(error, myPromise) // The error logger function requires the original promise to be passed in.
}

And here is how it looks with async/await:

try {
    const myPromise = await somePromise()
    //...
} catch (error) {
    errorLogger(error, myPromise) // Unfortunately, myPromise is not accessible in the catch block due to scope constraints.
}

So the question remains: How can I effectively access the promise within the catch block?

Answer №1

Make sure to assign myPromise() directly to the promise itself, not just what it resolves to when using await.

If you want to access the promise itself, store the function in a variable without using await. Then you can later use await to retrieve the resolved value.

const myPromise = somePromise();
try {
    const myValue = await myPromise;
    //...
} catch (error) {
    errorLogger(error, myPromise);
}

Answer №2

In order for our logging system to work effectively, it is necessary to pass the original promise to the error logger.

Some may question this approach, as there are various ways code can encounter errors even without a promise in sight. Ideally, all relevant information should already be present within the error object itself. It might be worth reconsidering your current logging method.

However, if you absolutely must adhere to this practice, one potential solution could involve:

try {
  const myPromise = somePromise();
  await myPromise.catch(err => { err.promise = myPromise; throw err; });
  …
} catch (error) {
  errorLogger(error, error.promise)
}

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

The Wikipedia API is unable to be loaded using the XMLHttpRequest

I have encountered this error before on this platform, and although I managed to fix it, I am seeking a more in-depth explanation of the solution. For a project where I am learning, I decided to create a Wikipedia Viewer application. The first step was to ...

Steps to effectively pass parameters in a function object literal

As a JavaScript beginner utilizing an object literal pattern, I am attempting to pass integers as min and max parameters to a function in order to retrieve a random number for use in another function called "interaction". However, I encountered the error m ...

Display Image After Uploading with AJAX

After spending nearly 3 hours working on implementing file uploads via AJAX, I have finally managed to get it up and running smoothly. Take a look at the code below: View <div class="form-horizontal"> <div class="form-group"> @Htm ...

Ways to stop two JavaScript files from running at the same time

After combining two JavaScript files, I am facing some issues. The first file handles validation while the second one has an ajax plugin for form submission after validation. When I include these files in the header section, they both run simultaneously. H ...

Having issues with the Carousel feature in Bootstrap 5.3.1 while using Angular version 15

I'm currently in the process of setting up a carousel on my homepage. It seems like everything is in place, but there's something missing. The initial image, text, and arrows all display properly, but they are non-functional. I have correctly imp ...

Is there a way to eliminate a specific input box using the jquery remove function?

I've been working on some code and have run into an issue. Currently, the remove function only works on one input box that is created with the append function. I would like it to be able to work on every input box generated through the append function ...

Add to MongoDB only if the entry does not already exist; otherwise, move on

Can I perform a conditional insert in MongoDB? //Pseudo code Bulk Insert Item : If Key exists Skip, don't throw error If key does not exist Add item If I do single inserts, it might return an error or insert into the collection. But is thi ...

Initiate Child Event within Parent Component

Before switching tabs in the parent component, I want the child tab to validate itself. My idea is to pass the onActive event from the parent to its children, <ClientInfo/> and <Details/>. This will allow the children to validate themselves a ...

How should a successful post request be properly redirected in React?

I am in the process of learning React and currently working on a small project. I have set up a NodeJS server to handle my requests, and now I am facing an issue with redirecting the user after a successful login. I successfully dispatch an action and upda ...

Tips for creating a responsive Youtube embedded video

Check out this website for a good example: If you take a look, you'll notice that the header youtube video is responsive - it automatically resizes when the window size changes. Here are the <iframe> codes: <iframe id="bluetube-player-1" fr ...

Issue with Translate3d functionality in fullpage.js not functioning as expected

Currently, I am in the process of constructing a website using fullpage.js with WordPress. Everything is functioning well except for one issue - when attempting to disable the plugin by using destroy() or changing setAutoScrolling to false, the translate3d ...

Understanding the reverse order of numbers displayed with while loop and innerHTML

function doItAgain() { var loopCount = 5; while(loopCount > 0) { var target = document.getElementById("target"); target.innerHTML = "LoopCount: " + loopCount + "& ...

Exploring and extracting values from nested arrays of objects in JavaScript and React

Hey there, I am having trouble getting the data from the backend server to display on a chart library. Can you please take a look at my code and help me out? const data = [ { id: "americano", data: [{x: "10",y: 10,}, {x: &quo ...

What could be the reason for Sequelize's findAll() method returning only a single object?

I am currently facing an issue where I can only retrieve one record out of many similar records when searching for products by brand and model name using Sequelize. This problem occurs even if there are multiple matching records, with the additional ones h ...

Using aliases in npm packages is not supported

I am working on creating an npm package that I want to use in another application. During development, I set a path in tsconfig for importing various modules instead of using a relative path. However, when I download my package into the test app, it is una ...

The error occurred while attempting to save the file to disk: 'setHeader() requires both a name and a value to be set.'

I am working on enabling image file uploads to the Node.js server in a MEAN Stack application. Utilizing ng-file-upload for the client-side angular directive has been successful so far. However, I have encountered an issue when attempting to pass the image ...

"I'm receiving the error message 'Unable to authenticate user' when attempting to connect to Supabase through the NextJS tutorial. What could be the

Recently, I embarked on a new project using NextJS and Supabase by following the tutorial available at this link. After completing the initial setup by updating the ".env.example" file to ".env.local" with the Supabase credentials, including creating a ne ...

Oops! Vue.js router configuration is throwing an error because it's unable to read properties of undefined when trying to access 'use'

Description: I have been working on a leaderboard web application using Vue.js. When I tried to launch the server on localhost after finishing my code, I encountered an error. The error message I received is as follows: Uncaught runtime errors: ERROR Cann ...

Preventing click propagation for custom react components nested within a MapContainer

I have developed a custom control React component for a map as shown below: export const MapZoom = () => { const map = useMap() const handleButtonClick = () => { map.zoomIn() } return ( <IconButton aria ...

Implementing theme in Monaco editor without initializing an instance

I recently developed a web application incorporating Monaco Editor. To enhance user experience, I also integrated Monaco for syntax highlighting in static code blocks. Following guidance from this source, I successfully implemented syntax highlighting wit ...