Day 18: Timeout

Dharan Ganesan - Aug 3 '23 - - Dev Community

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player