Value returned by Typescript

I have been attempting to retrieve a string from a typescript function -

private _renderListAsync(): string {
  let _accHtml: string='';
    // Local environment
    if (Environment.type === EnvironmentType.Local) {      

      this._getMockListData()
      .then((response) => {
        _accHtml = this._renderList(response.value);
        alert("1: " + _accHtml)
        })
        alert("3: " + _accHtml);
        return _accHtml;
    }
    else if (Environment.type == EnvironmentType.SharePoint || 
              Environment.type == EnvironmentType.ClassicSharePoint) {

      this._getListData()
        .then((response) => {
          _accHtml = this._renderList(response.value);
          alert("2: " + _accHtml);          
        })      
        alert("3: " + _accHtml);
        return _accHtml;
    }       
  }

Unfortunately, I am only able to receive the string value for alerts labeled as "1" and "2", but not "3" where it displays an empty alert, causing me difficulty in returning _accHtml from the function. What might be the issue here? Additionally, I have noticed that the alert with "3" appears before the ones labeled as "1" and "2". Can anyone explain why this is happening?

Answer №1

The occurrence of this behavior is a result of the asynchronous nature of ".then(...)". This method launches a new thread, allowing for the execution of subsequent lines in the code before returning the final result. As a consequence, the output may display 3 before 2 and 1. For optimal performance, I suggest utilizing Observables.

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

Utilizing Prisma Enum with Nest JS: A Comprehensive Guide

While working on my backend with Prisma and NestJS, I have encountered an issue. I defined an enum in Prisma that works fine in debug mode, but when I generate the Prisma client using nest build, I get an error. Object.values(client_1.RoomSharingType).join ...

Is it best to make a refactored/service method public or private in Typescript?

Objective: I need to refactor a method in my component that is used across multiple components, and move it to a service class for better organization. Context: The method in question takes a user's date of birth input from a profile form and convert ...

Can you explain the purpose of FunctionConstructor in typeScript?

As I delved into the Typescript Ecmascript source code, I stumbled upon this intriguing snippet: interface FunctionConstructor { /** * Creates a new function. * @param args A list of arguments the function accepts. */ new(...args: st ...

Creating a null array of a specific size can easily be accomplished in Typescript

When I use the splice method to add elements to an array at a specified index, I find myself creating a null array first in order to achieve this. If I use an empty array instead, the elements do not get pushed to the specific instance that I intended. Cur ...

Tsc encounters issues when interacting with AWS services

When attempting to compile TypeScript code into JavaScript using tsc, I encountered constant crashes specifically related to AWS code within the node_modules directory. Despite my efforts to resolve the issue by adding skipLibCheck to my tsconfig file, inc ...

Whenever I make a POST request to the API in Ionic 2, I encounter a "Connection refused (x192)" error

I have been struggling with an error in my code for the past two days and I can't seem to find a solution. Can someone please help me with this? The error message is as follows: [Error] WebSocket network error: The operation couldn’t be complet ...

What is the process for obtaining the form of an item and then adjusting the characteristics of each individual leaf property?

Consider this scenario: interface SomeObject { prop1: number; prop2: string; prop3: { innerProp1: number[]; innerProp2: string[]; innerProp3: { deeperProp1: string[]; deeperprop2: boolean; }, innerProp4: { [key: ...

Get React-table TS up and running on your local machine using VS Code

Objective: I am trying to get React-table working with TypeScript on my local computer. Challenge: The code is based on this page https://codesandbox.io/s/gkzg3?file=/src/makeData.ts However, when I attempt to apply the code on my local computer, I ...

What are the limitations of using a JS file within an Angular application?

I am struggling to integrate some js methods from a file into an angular application. Unfortunately, the browser is unable to recognize the js file. I have tried following the guidelines in this SO post, but the browser still cannot locate the file in the ...

Tips for invoking TypeScript code from Rust WebAssembly

Currently, I am considering transitioning a slow TypeScript library (jackson-js) to WASM using rust. This particular library has various dependencies, like reflect-metadata for example. These dependencies are already created and accessible on npmjs. The ...

TypeScript NodeJS Error: Unable to access the 'address' property as it is undefined

Having just started using TypeScript, I am puzzled by the error it's throwing. The VanillaJS version works perfectly, but when I transferred it to TypeScript and checked my index.ts file, the same error persisted even after compiling the TS code usin ...

What is the reason behind Angular's repeat filter only being able to access its own element within the return function?

I have successfully implemented some Angular code that is working, however, I am struggling to understand why it works. Coming from a C Sharp background and being new to JS and Typescript. <tr ng-repeat="colleague in Model.FilteredColleagueListModel | ...

Transforming a string such as "202309101010" into a date entity

Need to convert a string in the format "YYYYMMDDHHMM" (e.g. "202309101010") into a Date object in TypeScript? Check out this code snippet for converting the string: const dateString: string = "202309101010"; const year: number = parseInt(dateString.subst ...

What is the best way to showcase several images using Sweet Alert 2?

In the process of developing my Angular 2 application, I have incorporated sweet alert 2 into certain sections. I am looking to showcase multiple images (a minimum of two) at the same time in the pop-up. Does anyone have any suggestions on how to achieve ...

Is there a way to pass a form error to the parent component as a parameter in React?

I am just starting to learn React. I have created a form and I want to inform the parent component about any input errors that occur. I attempted to use the variable myError as a prop similar to how I used the next method, but unfortunately, it did not wor ...

Integration of Mocha with WebStorm

WebStorm offers a useful feature that adds a small arrow next to describe() and it() keywords when writing tests with Mocha, allowing for easy manual execution. However, there is a challenge: I require additional setup before each test, leading me to use ...

Struggling with the error message "Type 'ChangeEvent<unknown>' is not assignable to type 'ChangeEvent<MouseEvent>'" while working with React and TypeScript? Here's how you can tackle this issue

Within the App.tsx file, I encountered an issue with the Material UI Pagination component where it was throwing an error related to type mismatch. The error message stated: Argument of type 'ChangeEvent' is not assignable to parameter of type &ap ...

Is it considered beneficial to use Observable as a static class member?

Lately, I have been diving into a new Angular project and noticed that the common way to share state between unrelated components is by using rxjs Subject/BehaviorSubject as static members within the class. For instance: export class AbcService { privat ...

Having issues with JSON.stringify not properly handling every property within an object in Typescript

While using JSON.stringify in Typescript, I encountered an issue where not all properties of the outermost object were being stringified. Here is the code snippet that showcases the problem: class Criterion { '@CLASS' = 'xyz.abc.Criterio ...

What does the "start" script do in the package.json file for Angular 2 when running "concurrent "npm run tsc:w" "npm run lite"" command?

What is the purpose of concurrent in this code snippet? "scripts": { "tsc": "tsc", "tsc:w": "tsc -w", "lite": "lite-server", "start": "Concurrent npm run tsc:w npm run lite" } ...