0

I tried to use an async/await with promise

  async getReport(startDate: string, endDate: string){
    return await this.http
      .get<Report>(
        `https://localhost:44354/report?startDate=${startDate}&endDate=${endDate}`,
        this.httpOptions
      )
      .toPromise();
  }
getReports(startDate: string, endDate: string) {
    this.getReport('2020-03-20', '2020-03-26').then(response => {
      let lists= [
       {
        name: 'Opens',
        value: response .opens,
        color: 'green',
      },
        {
        name: 'Opens',
        value: response .opens,
        color: 'green',
      }];
    });

its possible to use the list outside the promise ? exemple if i want return list from my method getReports ?

Heptagram
  • 105
  • 1
  • 9
  • sorry i don't understand.. how i can make this – Heptagram Mar 27 '20 at 01:01
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jared Smith Mar 27 '20 at 01:10
  • No. Functions return synchronously, and the asynchronous data won't be there yet. Just pass the Promise around and await it or call .then on it as needed. – Jared Smith Mar 27 '20 at 01:11

1 Answers1

0

Return the promise, and lists from within the promise...

async getReports(startDate: string, endDate: string) {
    return this.getReport('2020-03-20', '2020-03-26').then(response => {
      let lists= [...];  // from the op
      return lists
    });
}

// in another method
async someMethod() {
  let lists = await this.getReports(dateA, dateB)
  console.log(lists)
}
danh
  • 62,181
  • 10
  • 95
  • 136
  • thank for your help, but it"s possible to call getReports from my Component like list = this.reportService.getReports(); because I have promise in return – Heptagram Mar 27 '20 at 01:17
  • I have this message -> 'await' expressions are only allowed within async functions and at the top levels of modules. – Heptagram Mar 27 '20 at 01:40
  • @Heptagram - sorry, see edit. It can be called with an await from within the module or from another module. You're also free to treat it's return like a promise, attaching a then() – danh Mar 27 '20 at 03:57