To create a timeout using a promise to cancel a long-running asynchronous operation, you can use the
Promise.race method in JavaScript. Here's a simple example:
function runWithTimeout(asyncFunction, timeout) {
return Promise.race([
asyncFunction(),
new Promise((_, reject) => {
setTimeout(() => {
reject(new Error('Operation timed out'));
}, timeout);
}),
]);
}
// Example usage:
const longRunningTask = () => {
return new Promise((resolve) => {
// Simulate a long-running operation
setTimeout(() => {
resolve('Operation completed');
}, 5000); // This operation takes 5 seconds
});
};
const timeoutMilliseconds = 3000; // Set a timeout of 3 seconds
runWithTimeout(longRunningTask, timeoutMilliseconds)
.then((result) => {
console.log(result);
})
.catch((error) => {
console.error(error.message); // Handle the timeout error
});
In this example:
The runWithTimeout function takes two arguments: asyncFunction, which is the asynchronous operation you want to run, and
timeout, which is the maximum time allowed for the operation to complete.
Inside runWithTimeout, we create a new Promise that rejects with a timeout error after the specified
timeout duration if the asynchronous operation does not complete in time.
We use Promise.race to race the original asyncFunction and the timeout Promise. Whichever resolves or rejects first will determine the outcome of the overall promise.
If the asyncFunction completes within the specified time, the
then block will execute, and you can handle the result.
If the asyncFunction takes longer than the specified
timeout, the catch block will execute with a timeout error message.
This approach allows you to cancel or timeout long-running asynchronous operations gracefully.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To create a timeout using a promise to cancel a long-running asynchronous operation, you can use the Promise.race method in JavaScript. Here's a simple example:
In this example:
This approach allows you to cancel or timeout long-running asynchronous operations gracefully.