The right way to use toPromise in angular 6

15,735

Solution 1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Sounds like you may want to look at this, you can collate an array of promises and can essentially "await" on all of them to complete before acting on the value.

myPromiseArray.push(this.http.get(url, {params: params}).toPromise()) Promise.all(myPromiseArray).then(alltheValuesInAnArray => {})

Solution 2

As you noticed, the result of .toPromise method is Promise object. In order to use async/await style, you need at first wrap your code with async function, by prepending async keyword to function, and then with await keyword tell your code to wait for async operation. In your case it's http request.

async function run(){
    try{
        const diagnostics = await (this.http.get(url, {params: params}).toPromise());
        // wait for asynchronous request
        console.log(diagnostics);
    } catch(err){
        // request failed
        console.error(err);
    }
}
run();
Share:
15,735
sandum
Author by

sandum

Updated on June 14, 2022

Comments

  • sandum
    sandum almost 2 years

    I'm trying to retrieve data from multiple http requests and i decided to avoid nested subscribe(). I just want to write code in async await style.

    const diagnostics = this.http.get(url, {params: params}).toPromise()
    console.log(diagnostics);
    

    But i get this:

    // ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)}
    

    Which i don't know how to handle to extract data.

    Is there a way to avoid callbacks like ?

    .then(res => {}).catch()
    
    • Amit Chigadani
      Amit Chigadani almost 6 years
      Why you want to return Promise and why not Observable? Any specific reason?
    • trincot
      trincot almost 6 years
      @AmitChigadani, one could ask why Observable when Promise will do the job fine.
    • Amit Chigadani
      Amit Chigadani almost 6 years
      @trincot Because Observable is more rich than Promise and could do more jobs. And By default all http requests return an Observable.. So why should we convert it to Promise and then return.
    • trincot
      trincot almost 6 years
      True, but promises can benefit from the nice async/await syntax.
    • madjaoue
      madjaoue almost 6 years
      @sandum Are you looking for a a pure promise style answer ?
    • trincot
      trincot almost 6 years
      Sandum, please show how you deal with multiple requests: do you need to wait for the first to initiate the next (with maybe a result from the first one), or do you want them all to be launched in parallel?
  • trincot
    trincot almost 6 years
    Why complicate things with Promise.all when in OP is speaking about one promise only?
  • Jake Kalstad
    Jake Kalstad almost 6 years
    He mentions multiple HTTP requests ---otherwise he could simply drop the toPromise() call entirely and just use the value I'd assume--- This is incorrect, angular http.get is actually returning an observable which I didn't think about.
  • sandum
    sandum almost 6 years
    @JakeKalstad i think this is a really good solution. We can use promises and Promide.all() to join them instead of using multiple nested subscribes.
  • SirDieter
    SirDieter almost 6 years
    Is there any reason not to create an observables array and use the RxJS operator forkJoin and subscribe to the resulting observable?