setTimeout() – async / await – Typescript / Angular application

Wait for component load with less time possible. (draft)

Abstract

I have angular app with registered components linked in some Map objects…

Others services and/or components need, on startup, to check if one or more components are registered and, if not, throw an exception.

Problem

On startup when checks if component exists one exception is generate because component is not completely load.

first solution …setTimeout

incapsulate check function/s into setTimeout and wait 1s (1000 ms) or even 2s; but if the function is called 5, 10 or even 20 times, we must wait for 20 or, even, 40 seconds …
… even if about 80% are already load…

second solution … async / await with timeout

With only await the risk is to wait a component that will never be load (es: classic typing error -> wait debugcomp but real component name is debugComp) and app freeze.

my solution … async / await with timeout

Probably not the better solution but work quite well…

The idea is setting a max timeout, es: 3s, set timeout interval, es: 50ms:

  • await check function max 3s
  • check function every 50ms test if component exists
    • if not exists call itself after 50ms
    • if component is load -> resolve Promise
    • if after 3s component not exists break loop and resolve Promise and probably throw new error
typescript code in angular class
// class function
async myFunc(mypar: any) {
    try {
      // ... your code
      const test = await this.awaitresolve(par1, par2, ..., 3000);

      if (!test) {
        // not test throw exception
        throw new Error('Your test failed');
      }
      // ... your code
   }
}

this.awaitresolve

awaitresolve(par1, par2, ..., timeout: number): Promise<myObject> {
    return new Promise((resolve, reject) => {

      const interval = 50;
      const targetcheck = myresult2test // es: mymap.get(par1);
      // new timeout setting es: form 3000 to 2950
      const newtimeout = timeout - interval;

      if (!targetcheck && timeout > 0) {
        // not checked
        setTimeout(() => {
          resolve(
            this.awaitresolve(par1, par2, ..., newtimeout)
          )
        }, interval);  // <-- only 50ms
      } else {
        // exist in mymap
        resolve(targetcheck as myObject);
      }
    });
  }

At the moment this code is not tested in production environments but will be asap in the future.

Probably evolution will be merge in FIFO queue to manage events driven app.