Swapping out the standard if/else logic for try/catch error

I'm facing a challenge in removing the then statements from this code snippet and replacing all catches with try/catch statements. I'm struggling to figure out how to handle the then statements.

export class WelcomePageContribution implements IWorkbenchContribution {

    constructor(
        @IInstantiationService instantiationService: IInstantiationService,
        @IConfigurationService configurationService: IConfigurationService,
        @IEditorService editorService: IEditorService,
        @IBackupFileService backupFileService: IBackupFileService,
        @IFileService fileService: IFileService,
        @IWorkspaceContextService contextService: IWorkspaceContextService,
        @ILifecycleService lifecycleService: ILifecycleService,
        @ICommandService private readonly commandService: ICommandService,
    ) {
        const enabled = isWelcomePageEnabled(configurationService, contextService);
        if (enabled && lifecycleService.startupKind !== StartupKind.ReloadedWindow) {
            try {
                const hasBackups = await backupFileService.hasBackups();
                const activeEditor = editorService.activeEditor;
                if (!activeEditor && !hasBackups) {
                    const openWithReadme = configurationService.getValue(configurationKey) === 'readme';
                    if (openWithReadme) {
                        // Your remaining code here
                    } else {
                        // Your alternative code here
                    }
                }
            } catch (error) {
                console.error('An unexpected error occurred:', error);
            }
        }
    }
}

so that the entire thing reads more like this..

const enabled = await isWelcomePageEnabled(configurationService, contextService);
if (enabled && lifecycleService.startupKind !== StartupKind.ReloadedWindow) {
    const hasBackups = await backupFileService.hasBackups();
    const activeEditor = editorService.activeEditor;
    if (!activeEditor && !hasBackups) {
        const openWithReadme = configurationService.getValue(configurationKey) === 'readme';
        if (openWithReadme) {
            // Your awaited code here
        }
  }
}
...

Answer №1

It seems like your second block of code is heading in the right direction. When then is called on a promise, you should use await instead of then. Save the result of the function that then was previously called on to a variable. Then, move the code from the callback into the then section below the await, keeping the same indentation level. Whenever you use await, consider wrapping it in a try/catch block, putting the equivalent of the catch callback inside the catch block.

For example:

fetchData().then(data => {
  console.log(data)
}).catch(err => {
  console.error(err)
})

can be rewritten as:

try {
  const data = await fetchData()
  console.log(data)
} 
catch (err) {
  console.error(err)
}

The challenge in your specific case is that the code is within a class constructor, which unfortunately cannot be made async.

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

Updating the HTML class with JavaScript

My HTML class has two classes $(document).ready(function() { $(".container").hover(function() { $('.green').addClass('display-on'); }); $(".container").mouseleave(function() { $('.black&apos ...

Unable to observe modifications in json file within java project (jsp)

I am currently using IntelliJ IDEA to develop a web project with JSP. I retrieve data from a file called "customer.json", and when I click on a button, I update this file in the backend. However, after trying to fetch the updated data again, it still reads ...

I am puzzled by the issue with my logic - the button only changes once and then the onclick function ceases to work

I am having an issue with a button that should switch between displaying temperatures in Fahrenheit and Celsius when clicked. It works for the first two clicks, but on the third click, it stops working even though I've set the class back to .temp. $( ...

What causes JavaScript to be unable to run functions inside other functions?

Functional languages allow functions to be executed within the argument brackets of nested functions. In JavaScript, which drew inspiration from Scheme, what is the equivalent? f( f ( f ( f))) console.log( 1 + 1 ) //2 How does JavaScript execut ...

Transmit information to Flask server using an AJAX POST call

I'm completely new to Ajax requests. I'm trying to send data from a webpage to my Flask backend using an Ajax request, but I can't get anything to show up in the backend: Here is the request code I am using: function confirm() { cons ...

Executing a protractor test on Safari results in the message "Angular was not located on the webpage https://angularjs.org/"

Recently, I encountered an issue while trying to run a Protractor test on Safari, even when following the official example provided at http://www.protractortest.org/. Below are my conf.js and todo-spec.js files. The problem arises when I set browser.ignor ...

Loop through an array of div IDs and update their CSS styles individually

How can I iterate through an array of Div IDs and change their CSS (background color) one after the other instead of all at once? I have tried looping through the array, but the CSS is applied simultaneously to all the divs. Any tips on how to delay the ...

Saving the initial and final days of each month in a year using javascript

I am trying to create an array of objects that contain the first and last day of each month in the year. I have attempted a solution but have hit a roadblock and cannot achieve the desired results. module.exports = function () { let months_names = ["j ...

Discovering the ASP.NET Core HTTP response header in an Angular application using an HTTP interceptor

I attempted to create a straightforward app version check system by sending the current server version to the client in the HTTP header. If there's a newer version available, it should trigger a notification for the user to reload the application. Ini ...

Using Javascript to prevent css from changing the display

I want to make some CSS adjustments to a single element using a single script, but I want all the changes to be displayed at once. For example: $("#someelement").css({width:"100%"}); //this change should not be displayed $("#someelement").width($("#someel ...

Issue encountered while attempting to retrieve data from a local json file due to Cross-Origin Resource Sharing

I'm attempting to fetch and display the contents of a JSON file on a webpage, but I'm encountering this error message: Access to XMLHttpRequest at 'file:///C:/Users/bobal/Documents/htmlTry/myData.json' from origin 'null' has ...

Tips for halting the live graph plotting based on a specific condition with canvas js

I have a piece of code that generates a live graph based on probabilities. I am looking for a way to stop the plotting process as soon as a specific condition is met. <script> window.onload = function () { var dps = []; // dataPoints var c ...

Using jQuery to create dynamic elements that fade out with timers

My website has a simple message system that displays messages in a floating div at the top of the page. Each message is supposed to fade out after a certain amount of time, but I want users to be able to pause the fading process by hovering over the messag ...

What is the proper way to retrieve multiple property values stored in a property name using getJSON

I'm having trouble getting multiple languages to work in my code. Could someone assist me and provide guidance on how to write multiple choices for the property name language? When I input code like this to display only Dota 2 games in English, every ...

Getting environment variables on the client side in Next.js: A step-by-step guide

How can I retrieve an environment variable in my Next.js application and pass the data into datadogRum.init? // _app.tsx import React from "react"; import { useEffect } from "react"; import type { AppProps } from "next/app"; ...

Increment the text counter following the uploading of an image file with html format

I have a form in which I am checking the character limit that a user can input into a text field using the 'onkeyup' attribute to update it in real time. Now, I want to achieve a similar function for image uploading. When a user selects an image ...

Verifying the Presence of an Image in the Public Directory of Next JS

My TypeScript Next.js project contains a large number of images in the public folder. I am wondering if there is a way to verify the existence of an image before utilizing the <Image /> component from next/image. I have managed to achieve this using ...

What is the best way to create a function that can securely search for a URL containing parameters while ensuring type safety?

I am working on a NextJS/React application. We have a large object containing internal URLs, each with a createPath function that looks similar to this: const URLS = { dashboard: { createPath: ({ accountNumber }: { accountNumber: string }) => ...

Turning a Two Dimensional Object or Associate Array into a Three Dimensional Object using Javascript

Is there a method to transform the following: var stateDat = { ME: ['Maine',1328361], etc. }; Into this structure dynamically within a function? var stateDatHistory = { 1:[ ME: ['Maine',1328361], etc. ], 2:[ ME: ['Maine& ...

Tips for incorporating ajax to load a new webpage into a specific div container

I have a website with two pages. I want to load Page 2 into a div on Page 1 and then display Page 2 when clicked on. I'm attempting to implement the following code, but it doesn't seem to be working for me. As a beginner, I apologize if this is a ...