DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 18: Timeout

Question

Write a function promiseTimeout that takes an asynchronous operation represented as a Promise and rejects it after a specific time if it hasn't been resolved yet.

function promiseTimeout(promise, timeout) {
  // Todo add your code
}

  // Simulating an asynchronous operation 
const delayBy2000 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve({ name: 'John Doe', age: 30 });
  }, 2000); // Resolves after 2 seconds
});

const timeout = 1500; // Set timeout for 1.5 seconds
const promiseWithTimeout = promiseTimeout(delayBy2000, timeout);

promiseWithTimeout
  .then((data) => {
    console.log('Promise resolved:', data);
  })
  .catch((error) => {
    console.error('Promise rejected:', error.message);
  });
Enter fullscreen mode Exit fullscreen mode

🤫 Check the comment below to see answer.

Top comments (1)

Collapse
 
dhrn profile image
Dharan Ganesan • Edited

There are multiple way to answer this

  • First answer:
function promiseWithTimeout(promise, timeout) {
    return new Promise((resolve, reject) => {
        // Start the original promise
        promise.then(resolve).catch(reject);

        // Set a timeout to reject the promise if it hasn't resolved within the specified time
        setTimeout(() => {
            reject(new Error(`Promise timed out after ${timeout} milliseconds`));
        }, timeout);
    });
}
Enter fullscreen mode Exit fullscreen mode
  • Second answer:
function promiseWithTimeout(promise, timeout) {
  // Create a new Promise that resolves when the input promise resolves
  const resolvedPromise = new Promise((resolve, reject) => {
    promise.then(resolve).catch(reject);
  });

  // Create a Promise that rejects after the specified timeout
  const timeoutPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
      reject(new Error('Promise timeout'));
    }, timeout);
  });

  // Use Promise.race() to wait for either the input promise or the timeout to settle
  return Promise.race([resolvedPromise, timeoutPromise]);
}
Enter fullscreen mode Exit fullscreen mode