Sobes.tech
Middle

Create a function that rejects the returned promise, passing the string "timeout_error" as the error, if it does not resolve within the specified timeout, or behaves normally as the original. @param {Promise} promise the original promise @param {Number} timeoutMilliseconds the timeout duration in milliseconds @return {Promise} a promise with the desired behavior function withTimeout(promise, timeout) { return new Promise((res, rej) => { const timeoutId = setTimeout(() => { rej("timeout_error") }) }) }

sobes.tech AI

Answer from AI

The function should create two competing promises: the original and a timeout that rejects after a specified time with the error "timeout_error". Then, it returns a promise that resolves or rejects with the first of these to settle.

function withTimeout(promise, timeoutMilliseconds) {
  return new Promise((resolve, reject) => {
    const timeoutId = setTimeout(() => {
      reject("timeout_error");
    }, timeoutMilliseconds);

    promise.then(
      (value) => {
        clearTimeout(timeoutId);
        resolve(value);
      },
      (error) => {
        clearTimeout(timeoutId);
        reject(error);
      }
    );
  });
}

This approach guarantees that if the original promise does not settle within the timeout, it will be rejected with the error "timeout_error". If it settles earlier, the timeout is canceled.