"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

Ensuring that all observables within a for loop have completed before moving on to the next block of code

Here is a scenario where the following code snippet is used: getPersons().subscribe( persons => { for (const person of persons) { getAddress(person.id).subscribe( address => { person.addres ...

Exploring the depths of TypeScript's intricate type validation

Could you please review the comments in the code? I am trying to determine if it is feasible to achieve what I need or if TypeScript does not support such functionality. I require type checks for my addToRegistry function. Play around with TypeScript in ...

The Art of Dynamic Component Manipulation in Angular

The current official documentation only demonstrates how to dynamically alter components within an <ng-template> tag. https://angular.io/guide/dynamic-component-loader My goal is to have 3 components: header, section, and footer with the following s ...

Conditional validation in Typescript based on the nullability of a field

I have come across the following code snippet: type DomainFieldDefinition<T> = { required?: boolean } type DomainDefinition<F, M> = { fields?: { [K in keyof F]: DomainFieldDefinition<F[K]> }, methods?: { [K in keyof M]: M[K] & ...

Passing data between Angular 2 components

Below is the component I am working with: @Component({ selector: 'myselector', providers: [ ], directives: [ ChildComponent], pipes: [ ], template: '<myselector>This is {{testEmitter}}</myselector>' }) export cla ...

Is it necessary to enforce a check for surplus properties in the return type of a function

In this particular scenario, the TypeScript compiler does not raise an error when a function returns an object with the type UserProfile even though the expected return type is UserProfileWithNoPermissions. Here's an example: interface UserProfile { ...

How to attach input to function invocation in Angular 2

Can we connect the @Input() property of a child component to a parent component's function call like this: <navigation [hasNextCategory]="hasNextCategory()" [hasPreviousCategory]="hasPreviousCategory()" (nextClicked)="next ...

Typescript patterns for creating a modular library design

Transitioning a JavaScript project to TypeScript has been challenging for me, especially when it comes to establishing a solid design pattern for the library's modularity. Main Concept The core functionality of my library is minimal. For instance, i ...

Is there a way to utilize multiple HTML templates with the same TypeScript file?

Is it possible to use different HTML templates for the same TypeScript file, based on an expression in the constructor? I am looking for something like this: <div class="container-fluid"> <app-teste1 *ngIf="teste == '1'> & ...

Exploring Angular: How does Number.isNaN handle non-empty strings?

Within my component, there is a dropdown menu that allows users to choose a value. Upon selecting an item from the dropdown, a function called onDropdownChange is triggered. The parameter passed to this function can either be a string ("Please select an op ...

Determine data types for functions in individual files when using ElysiaJS

Currently, I am utilizing ElysiaJS to establish an API. The code can be found in the following open-source repository here. In my setup, there are three essential files: auth.routes.ts, auth.handlers.ts, and auth.dto.ts. The routes file contains the path, ...

Why is TypeScript giving an error about an undefined object key, even though the key was assigned a value in the previous command?

type MaybeThereIsAValue = { [p: string]: string | undefined } ... let bar: MaybeThereIsAValue = {}; const key = "carpe"; bar[key] = "diem"; const why = bar[key]; // why is string | undefined I am confused as to why why is showing ...

How can we retrieve the target element for an 'onSelectionChange' DOM event in Angular 6?

When using Angular 6, I want to retrieve the "formControlName" of the corresponding element whenever the selection changes. HTML <mat-form-field *ngIf="dispatchAdviceChildForAdd._isEditMode" class="mat-form-field-fluid"> <mat-select ...

Utilizing event binding with ngForTemplate in Angular 2

Imagine having a straightforward list rendering component: import {Input, Component } from 'angular2/core' @Component({ selector: 'my-list', template: ` <div *ngFor='#item of items' (click)='onItemClicked(i ...

Testing the Angular router-outlet using Jasmine

When testing web-app navigation using Jasmine spec with RouterTestingModule, I am facing challenges with nested fixture.whenStable().then(() => {}). For instance: After clicking on multiple links where the router-outlet changes the displayed component ...

Using Angular 10 to make an HTTP POST request, with the goal of appending a string

Whenever I try to send a post request to an api endpoint, I keep encountering an error with status code 500. name: "HttpErrorResponse" ok: false status: 500 statusText: "Internal Server Error" Below is the code I am using: var selected ...

Retrieving JSON data through HttpClient in Angular 7

I am attempting to retrieve information from this specific URL. The data obtained from this URL is in JSON format. This particular file is named data.services.ts: import { Injectable } from '@angular/core'; import { HttpClient } from '@an ...

Is it best practice to use the AngularFirestoreCollection for updating Firestore items in AngularFire?

Within my application, I have a list that necessitates the use of an "or" condition. However, according to the documentation: "In this case, you should create a separate query for each OR condition and merge the query results in your app." Consequently ...

The back-end is not receiving the HTTP Get call, even though the URL is functional in the browser. The error message states that the JSON is

The backend function is functioning properly as both Postman and Swagger are able to call it without any issues. I decided to capture the URL string displayed in the error message and pasted it into a browser. Surprisingly, it successfully reached the bac ...

How can I effectively filter the data returned by consuming an API in JSON through an Angular service?

My Angular 6 project includes a UsersService that is injected into the UsersComponent. Originally, the component displayed mock data in the form of a string array. However, it now consumes JSON data from an API provided by JSONPlaceholder via the UsersSer ...