How to retrieve values from a Promise in Angular?

I was trying to fetch values from Pouch DB through Angular , based on specific attribute values , say “fetch all records with the name ‘Vijay’”.

I faced a difficulty in doing it.

Pouch DB has a neat API pouchdb.find() which returns a Promise and not the actual result.

It is an asynchronous method. The result may take some time to be returned. And it should be retrieved from the Promise. How can this be done so that angular waits until the result is ready and then renders it on the template?

Here comes the rescue:

The words ‘await’ and ‘async’.

Below are the steps of how to use them :

Step 1:

Write the template code .

Here user enters a ‘name’ value in a textbox and clicks on ‘Search’ button .

This is a generic code using angular reactive form.

<h2>Search By Name</h2>>
<form  [formGroup]="pouchform">
<label>Enter Name</label>
<input formControlName="name"/>
<br>
<button (click)="search()">Search</button>

<table>

  <tr *ngFor="let row of result">

    <td>{{row.name}}</td>
    <td>{{row.emailid}}</td>
  </tr>
</table>

</form>

Step 2 :

Return an ‘async’ method in the component :

Here is the typescript code:


  async search() {



    let records = await this.getForms(this.pouchform.value.name);


    this.result = records.docs;


  }

  getForms(name) {

//this method returns a Promise
    return this.pouchdb.find(

      {
        selector: {
          name: searchName
        }
      }
    )

  }

Notice the words ‘async’ and ‘await’.

In the above code the method getForms() fetches records from pouch db and returns the result as a ‘Promise’. To retrieve the actual records follow these steps:

1) Use the word ‘await’ before the method call (which returns a Promise)

2) Declare the original method as ‘async’ (the method which is invoked on button click).

These two will make sure that angular template gets the actual result from the promise.

That’s it!

Await and Async to retrieve values from a Promise!


Posted

in

, , ,

by

Tags:

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading