Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Best way to override or extend javascript await?

Every time I use await in my code, I want a loading screen to appear. It’s getting tiresome having to always write:

this.loadingDivOn();
await fetch(//do something);
this.loadingDivOff();

or

this.loadingDivOn();
const response = lastValueFrom(await this.http.delete(`/calendar/${id}`));
this.loadingDivOff();

What would be nice is to override the behavior of await
to something like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

loadingDivOn() 
await(some operation) 
loadingDivOff()

What have you done to reduce code duplication? Note this has to handle any type of operation after await, not just fetch.

>Solution :

Create a function that accepts a Promise as parameter and pass your promises into that function

async function promiseWrapper(apromise) {
  try {
    this.loadingDivOn();
    return await apromise;
  } finally {
    this.loadingDivOff();
  }
}



let fetchresponse = await promiseWrapper(fetch(...));
let delresponse = await promiseWrapper(this.http.delete(...));

Using try ... finally it’s guaranteed that this.loadingDivOff() will always be called, regardless of whether apromise resolves or rejects. But not having a catch block in the promiseWrapper will pass on any exception thrown by apromise

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

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

Continue reading