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);
});
🤫 Check the comment below to see answer.
Top comments (1)
There are multiple way to answer this