matheus-rodrigues00 / utils

✨ Library to commonly used cross-projects utilities methods ✨
17 stars 11 forks source link

Timeout method in promises.ts has nested promises and doesn't abort promise after timeout #63

Open superbrobenji opened 2 hours ago

superbrobenji commented 2 hours ago

currently the timeout function looks as follows:

function timeout<T>(promise: Promise<T>, time: number = 8000) {
  return new Promise((resolve, reject) => {
    const timeout_id = setTimeout(
      () => reject(new Error(TimeoutErrors.TIMEOUT_ERROR_MESSAGE)),
      time
    );

    promise
      .then(response => {
        clearTimeout(timeout_id);
        resolve(response);
      })
      .catch(err => {
        clearTimeout(timeout_id);
        reject(err);
      });
  });
}

at the moment it, the passed promise is nested within a new promse that's returned. it will return on settlement of the passed promise or it will reject on the settlement of the settimeout. this logic does not abort the passed promise. If it's an api request for instance, the request still takes place, we just no longer wait for the response.

A solution would be to instead create an abortPromise with an abortController, and Promise.race it against the passed promise. this way we no longer have nested promises, and the promise gets aborted entirely, not just ignored

github-actions[bot] commented 2 hours ago

🎉 Congratulations on opening the first Issue for @teteu/utils! 🎉