Vivek Nuna
Vivek Nuna

Reputation: 1

How to wait for return of a function in TypeScript?

I have a method which is returning a value and I'm assigning the return value to a variable. the function returns proper value but the variable is not set with the return value. But if I set this.size inside the function I get proper value. I'm calling this.searchData function from many functions, So I cannot do this(in this case I will have to use multi if statements), So is there any way to get the return value from the function. I thought to use timeout is there any other way around?

searchSize(event): void {
    this.sizes = this.searchData(event, AppConsts.size);
}

searchData(event, property): any {

    this._serviceProxy.getProperties(
        property,
        event.query,
        event.query
    ).subscribe((result) => {

        console.log(result.items);
        return result.items;
    });
}

Upvotes: 1

Views: 10798

Answers (2)

basarat
basarat

Reputation: 276393

How to wait for return of a function in TypeScript?

Step 1

return the observable

 return this._serviceProxy.getProperties( // note : return
        property,
        event.query,
        event.query
    ).subscribe((result) => {

        console.log(result.items);
        return result.items;
    });
}

Step 2

subscribe to the returned value e.g.

searchData(something).subscribe

Upvotes: 0

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250416

For cleaner simpler code, you could also use the async/await syntax. You have to convert your observable to a promise, and then you can await the result:

import * as rx  from 'rxjs'
class ListResultDtoOfPropertyDTO{
    items: any[]
}
class Test {
    sizes: any[];
    _serviceProxy : {
        getProperties() : rx.Observable<ListResultDtoOfPropertyDTO>
    }
    async searchSize(event): Promise<void> {
        this.sizes = await this.searchData(event);
    }

    async searchData(event): Promise<any[]> {
        var result = await this._serviceProxy.getProperties()
            .toPromise()

        console.log(result.items);
        return result.items;
    }
}

Explanations:

Typescript allow a nicer syntax around waiting for results from a Promise. The syntax does not apply to Observables (hopefully in the future it will), we can however convert the Observable to a promise in this case. For more information about async/await syntax, have a look here

Upvotes: 2

Related Questions