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
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