"Error: Variable becomes undefined due to the implementation of async-await in TypeScript

There has been a persistent issue I've been dealing with for some time now. The problem lies in the fact that vm_res is undefined within the async update_vm_raw_device function despite the function running smoothly. As a result, the value being updated ends with

/mnt/tank/ds/test_file_test_VM_undefined
. Pay close attention to the "undefined" at the end.

async customSubmit(value) {
  const path = `${value.raw_file_directory}/${value.raw_filename}_${value.name}`;
    const payload = {}
    const vm_payload = {}
    ......SNIP..........
    this.ws.call('vm.get_sharefs').subscribe((get_sharefs)=>{
      if(!get_sharefs){
        this.ws.call('vm.activate_sharefs').subscribe((sharefs)=>{
          this.ws.call('vm.create', [vm_payload]).toPromise().then(vm_res => { 
            // Despite assignment happening here, this.vm_res remains undefined in the async update_vm_raw_device function.
            this.vm_res = vm_res;
          });
        }
      )
      }
      else {
        this.ws.call('vm.create', [vm_payload]).toPromise().then(vm_res => {
          this.vm_res = vm_res;
        });
      }
    },)
    await this.update_vm_raw_device(vm_payload, this.vm_res);
  }

  async update_vm_raw_device(vm_payload: any, vm_res: number) {
  vm_payload.path = `${vm_payload.path}_${this.vm_res}`    
   await this.ws.call('datastore.update'[vm_payload])])).toPromise().then(
       res=>{});}

Answer №1

async/await has no relevance in this situation.

It seems that this.vm_res is solely being assigned a value within a subscribe function, which will not be executed before calling this.update_vm_raw_device().

Were you intending to move the invocation of this.update_vm_raw_device() inside the subscribe handler? Maybe after assigning the value?

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

Using React with Typescript and ie18next to fetch translations from an external API

In the past, I have experience working with i18next to load translations from static json files. However, for my current project, I need to load all translations from an API. How can I achieve this? Additionally, how can I implement changing the translat ...

Improving the method of retrieving RTK result within getServerSideProps

Currently, I am utilizing RTK Query to make an API call within my getServerSideProps function. While I can successfully retrieve the result using the code snippet provided below, I find the process somewhat awkward. Additionally, the result lacks proper ty ...

Step-by-step guide on defining a context variable within a template

I am looking for a way to make my page dependent on a single model object emitted from an Observable. If it was a list, I would use <div ngFor="let currentListItem of myObservable | async" > However, since I only have one model and not a list, ngFo ...

Encountering TS2339 error while attempting to append a child FormGroup within Angular framework

I'm currently working with Angular8 and facing an issue while attempting to include a child FormGroup to a form using the addControl method: this.testForm = new FormGroup({ id: new FormControl(0), people: new FormGroup({ } ...

Using object bracket notation in TypeScript to retrieve values from props with the help of string interpolation

I encountered an issue in my code while attempting to utilize a variable within my TSX component. This problem arises due to the dynamic props being passed into the component, which are always a string that matches one of four keys in the "characters" obje ...

Receiving error in TypeScript while using the 'required' attribute in the input field: "Cannot assign type 'string | undefined' to parameter expecting type 'string'"

In my TypeScript code, I am currently in the process of transitioning from utilizing useState to useRef for capturing text input values. This change is recommended when no additional manipulation necessitating state or rerenders is required. While I have ...

Post-upgrade to .Net Core 3.1, the Liveness and Readiness probe encountered failures

Recently, I updated my .Net Core from version 2.1 to 3.1. However, after the upgrade, the Liveness and Readiness probe to the pods failed. Below is an excerpt from my docker file: FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base WORKDIR / ...

Angular's Mysterious Pipe

When navigating to the indice page, I want to adjust the number formatting in the cours column to display two decimal places. For instance: 11345.654589 should be displayed as 11345.65. https://i.stack.imgur.com/tjvWb.png To achieve this, I have created ...

Different Categories of Array Deconstruction

While iterating through an array, I am utilizing destructuring. const newArr = arr.map(({name, age}) => `${name} ${age}`) An error occurs in the above code stating: Binding element 'name' implicitly has an 'any' type To resolve th ...

Pause until the user selects either the confirm or deny option before proceeding with the next action

As a beginner in Angular, I am seeking help with my code structure. I have three files: WarningComponent (which displays a warning modal using Bootstrap), modalService (responsible for opening modals), and votingComponent. Within the votingComponent, ther ...

Substituting generic type in inherited class method results in error message: "Property 'x' in type 'y' cannot be assigned to the property with the same name in the base class 'Parent'."

Here is the code snippet I am working with: class BaseModel { protected getAttribute<T extends BaseModel>(): keyof T | null { return null; } } class Payment extends BaseModel {} class Item extends BaseModel {} class Sale extends BaseModel { ...

No indication of component statuses in the augury feature

Augury is a useful Chrome extension for debugging Angular applications. However, I have encountered an issue where it is not displaying any states currently. My setup includes Angular version 5.1.0 and Augury version 1.16.0. ...

Experiencing the `Cannot access a closed file` error while attempting to asynchronously copy files

When attempting to asynchronously copy multiple files, an error is encountered: System.ObjectDisposedException: Cannot access a closed file. The method used for copying is as follows: public Task CopyAllAsync(IList<ProductsImage> productsImage) { ...

The Angular HttpClient is unable to retrieve the message from the response body

I am in the process of implementing a post request using HttpClient to send data to my getFeedback endpoint and display the response in my application. I have a codeService and a dashboard component. Here is the code snippet for the post method in my code ...

Is there a way to verify a user's login status?

Currently, I am working on an angular 13 project and incorporating @angular/fire 7 into my development process. I have developed a service with various functions for injection. Below is the code snippet: import { Injectable } from '@angular/core&apos ...

Is it possible to establish a specific many-to-many relationship using Prisma?

In the Prisma documentation, it states that the set function can be used to override the value of a relation. const user = await prisma.user.update({ where: { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="73121f ...

What is the process for passing information to a nested component structure with parent-child-child relationships?

I am facing an issue with three nested components (C1, C2, C3) where C2 is called within C1 and C3 is called within C2. My goal is to pass data from C1 to C3 using property binding. In the template of C1, I successfully bound a variable that I can access ...

Using Typescript to extract elements from one array and create a new array

I have a set of elements "inputData" , and it appears as follows : [{code:"11" , name= "test1" , state:"active" , flag:"stat"}, {code:"145" , name= "test2" , state:"inactive" , flag:"pass"}, {code1:"785" , name= "test3" , state:"active" , flag:"stat"}, .. ...

retrieving information from an array nested within a JSON object in an Angular application

I am struggling to retrieve two specific values from a JSON object. The content of the JSON is as follows: [ { "type":"session_start", "properties":[ { "property":"activity&q ...

Error: Value Loop Detected in AngularFire Document ID

I encountered a "Cyclic Object Value" Error while working on an Angular Project with AngularFire. As a beginner with Firebase, I haven't been able to find a straightforward solution to this issue. The error arises when I query a collection in my Fire ...