Typescript: Delay code execution until a function has completed running

I've encountered an issue with my code that involves calling a function. Here is the snippet of code in question:

this.getAllOptions(questionID);
console.log("++++++++++++++++++++++++++++++++");
console.log(this.result);

The task of this function is straightforward - it invokes a service, which then returns an array of objects. What I specifically require from this returned data is just the "item.Content," formatted as a string. Below is the relevant code snippet:

result: string;
getAllOptions(question_ID){

    this.result = "";

    this._service.getOptionsQuestion(question_ID)
        .subscribe( data => {
            data.forEach(item => {
            console.log(item.Content);
            this.result += item.Content;
            });
        });
}

However, a problem arises where the lines of code after invoking the "getAllOptions()" function are executed prematurely. I am seeking a way for those subsequent lines to wait until the function has completed execution.

Is there a solution to accomplish this?

Answer №1

Patience is key when waiting for data to arrive. As soon as the getOptionsQuestion function finishes executing, the observable it generates has not yet received any data, so the callback provided to the subscribe method remains inactive.

There are various strategies one can employ to wait for the data. Personally, I find the async/await syntax in Typescript to be my favored choice as it enhances code readability:

import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import * as rsx from 'rxjs'

class Test {
    // Declaration of a dummy service
    _service : {
        getOptionsQuestion(nr: number): rsx.Observable<Array<{Content : string }>>
    }

    result: string;
    async getAllOptions(question_ID: number){

        this.result = "";
		const data = await this._service.getOptionsQuestion(question_ID).toPromise()

        data.forEach(item => {
            console.log(item.Content);
            this.result += item.Content;
        });
    }
    async otherMethod (questionID : number){
        await this.getAllOptions(questionID);
        console.log("++++++++++++++++++++++++++++++++");
        console.log(this.result);
    }
} 

Answer №2

To solve the problem, one approach is to utilize a promise in the getAllOptions function.

result: string;

getAllOptions(question_ID): Promise<void>{
    let resolveRef;
    let rejectRef;

    //create a new promise. Save the resolve and reject reference
    let dataPromise: Promise<void> = new Promise((resolve, reject) => {
        resolveRef = resolve;
        rejectRef = reject;
    });
    this.result = "";

    this._service.getOptionsQuestion(question_ID)
        .subscribe( (data: any) => {
            data.forEach(item => {
            console.log(item.Content);
            this.result += item.Content;
            });
            // resolve the promise once result is populated
            resolveRef(null);
        });

    //return promise created.
    return dataPromise;
}


// execute the console logs on then part of the promise returned by getAllOptions
this.getAllOptions(questionID).then(() => {
    console.log("++++++++++++++++++++++++++++++++");
    console.log(this.result);
});

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

Getting the Full Error Message in Axios with React Native Expo

I'm encountering a network error while using Axios with React Native. Previously, when working with React JS on the web, I could console log the error or response and see all the details. However, in Expo, all I get is "Axios error: Network error" wh ...

Challenges arise with data updating following a mutation in @tanstack/react-query

As I work on building an e-commerce website using React, I have a specific feature where users can add products to their favorites by clicking a button. Following this action, I aim to update the profile request to display the user's information along ...

When using React MUI Autocomplete, make sure to handle the error that occurs when trying to filter options using the

I am trying to implement an autocomplete search bar that makes a custom call to the backend to search through a list of tickers. <Autocomplete multiple id="checkboxes-tags-demo" options={watchlis ...

What is the best way to interact with and modify the relationships of "many-to-many" fields in my database table?

As someone who is new to nestjs, I am working with two entities: @Entity({ name: "Books" }) @ObjectType() export class Book { @PrimaryGeneratedColumn() @Field() id: number; @Column() @Field() title: string; @ManyToMany(() => Auth ...

What is the correct way to utilize Array.reduce with Typescript?

My current approach looks something like this: [].reduce<GenericType>( (acc, { value, status, time }) => { if (time) { return { ...acc, bestValue: valu ...

Utilizing nested observables for advanced data handling

Consider the following method: public login(data:any): Observable<any> { this.http.get('https://api.myapp.com/csrf-cookie').subscribe(() => { return this.http.post('https://api.myapp.com/login', data); }); } I want to ...

What is the best way to extract information from a button and populate a form in AngularCLI?

I am currently attempting to enhance my Angular App by using a button to transfer information to a form upon clicking, rather than the traditional radio buttons or select dropdowns. My objective is to incorporate HTML content into the button (such as Mat-I ...

Using Fixed Patterns and Combining Types in an Interface

Presently, I am working with this interface: export interface User{ name: string birthday: number | Timestamp ... } When strictTemplates:false is enabled, I have no issue using this interface for server data retrieval with the birthday parameter in ...

Issue with Angular reactive forms when assigning values to the form inputs, causing type mismatch

I'm a beginner when it comes to reactive forms. I'm currently working on assigning form values (which are all string inputs) from my reactive form to a variable that is an object of strings. However, I am encountering the following error: "Type ...

Prevent Typescript from flagging unnecessary warnings about unassigned values that will never be assigned

One of my functions serves as a shortcut for selecting values from synchronous observable streams. The function in its entirety looks like this: export function select<T>(inStream: Observable<T>): T { let value: T; race( inStream, ...

Angular and WEB API experiencing issues with the update function synchronization

Currently, I'm developing a CRUD example using dotnet core and Angular. In the backend, I have implemented a function in the CarController.cs as shown below: CarController.cs [Route("UpdateCar")] [HttpPut] public IActionResult Put([ ...

Angular 7 error: No provider found for PagerService causing NullInjectorError

I have been struggling to get pagination working properly in my project. Below is the code I have written: pager.service.ts: import * as _ from 'underscore'; @Injectable({ providedIn: 'root', }) export class PagerService { ...

For each array element that is pushed, create and return an empty object

I am encountering an issue with an array where the objects are being generated by a push operation within a function. Despite successfully viewing the objects directly in the array, when I attempt to use forEach to count how many times each id uses the ser ...

What is the best way to loop through a formarray and assign its values to a different array in TypeScript?

Within my form, I have a FormArray with a string parameter called "Foo". In an attempt to access it, I wrote: let formArray = this.form.get("Foo") as FormArray; let formArrayValues: {Foo: string}[]; //this data will be incorporated into the TypeScript mod ...

No declaration file was found for the module named 'vue2-timepicker'

Overview I integrated the vue2-timepicker plugin into my Typescript/Nuxt.js application. However, I encountered an issue with importing vue2-timepicker. import timepicker from 'vue2-timepicker' Could not find a declaration file for module &apos ...

The sanitizer variable becomes null when accessed outside of the NgOnInit function in Angular using TypeScript

At first, I added DomSanitizer to the component: import { DomSanitizer, SafeResourceUrl} from '@angular/platform-browser'; Next, a class was created and included in the constructor: export class BlocklyComponent implements OnInit { primar ...

Inquiry regarding the return value of 'async-lock' in nodejs

I am utilizing the async-lock module in my typescript project to handle concurrency. However, I am encountering difficulties with returning the result within lock.acquire(...) {...}. Any guidance on how to resolve this issue would be greatly appreciated. ...

Leveraging Angular Observables for seamless data sharing across components

As I embark on developing my very first Angular app, I have encountered a challenge with filtering a list of book objects based on their gender attribute. The issue lies in sharing data between components – specifically the filteredData variable and the ...

Retrieving data from a form input that utilizes reactive checkboxes

Hey there, I am currently working on implementing a Reactive Form and facing an issue with fetching values from checkboxes. It seems that only the value of the first checkbox selected is being recognized while the others are not. Below is the snippet of my ...

When using react-chartjs-2 with NextJS and typescript to create a bar chart, an error occurred: TypeError - Attempting to access properties of an undefined object (specifically 'map

Encountering a console error stating TypeError: Cannot read properties of undefined (reading 'map') . As I am new to NextJS & Typescript, I am attempting to build a simple bar chart. Error message: react-dom.development.js?03cb:22839 Uncaugh ...