0

I am trying to get the data from my API call but using a Promise.

interface SomeType {
    status: string;
    other?: string; // not used - delete
}

indexStatus(indexName: string): string {
    // this.content = {};
    const returnedPromise = this.indexStatusCall(indexName)
        .then(returnData => {
            this.content = returnData;
            return returnData;
        });
    this.content = returnedPromise;
    console.log("----this.content: ", returnedPromise);
    return returnedPromise[0];
}

indexStatusCall(indexName: string): Promise < SomeType > {
    return this.http.fetch('http:API-PATH/indices/' + indexNameReplaced + '?format=json&h=status')
        .then(response => response.json())
        .then(data => {
            return data;
        });
}

And here is what the console.log is showing

enter image description here

How can I get to my "status" value?

Chris Jackson
  • 718
  • 1
  • 6
  • 14

1 Answers1

0

You need to wait for the promise to resolve before you can access your result. So your indexStatus can't return a string, it must return a Promise<string>. That's also why you're seeing the promise in your console.log.

With async/await

async indexStatus(indexName: string): Promise<string> {
    const data = await this.indexStatusCall(indexName);
    this.content = data;
    console.log("content", this.content);
    return data.status;
}

By chaining promises

indexStatus(indexName: string): Promise<string> {
    return this.indexStatusCall(indexName)
       .then(data => {
          this.content = data;
          console.log("content", this.content);
          return data.status;
       });
}

For more reading on Promises, MDN has some great tutorials on how promises work. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Nate Bosscher
  • 397
  • 2
  • 10