---
title: "How to create a timeout using a Promise to cancel a long-running asynchronous operation?"  
description: "How to create a timeout using a Promise to cancel a long-running asynchronous operation?"  
author: "Revati S Misra"  
published: 2023-09-26  
updated: 2023-09-26  
canonical: https://www.mindstick.com/forum/159924/how-to-create-a-timeout-using-a-promise-to-cancel-a-long-running-asynchronous-operation  
category: "javascript"  
tags: ["javascript", "promise"]  
reading_time: 2 minutes  

---

# How to create a timeout using a Promise to cancel a long-running asynchronous operation?

How to create a [timeout](https://www.mindstick.com/forum/159429/sql-query-returns-a-timeout-expired-error) using a [Promise](https://www.mindstick.com/forum/158328/what-is-a-promise-in-javascript-and-how-do-you-use-it) to [cancel](https://answers.mindstick.com/qa/94501/how-can-i-cancel-my-singapore-flight-ticket) a [long](https://www.mindstick.com/articles/44565/white-wedding-dresses-long-prom-dresses)-running [asynchronous](https://www.mindstick.com/blog/178/synchronous-and-asynchronous-command-execution-in-c-sharp-dot-net) [operation](https://www.mindstick.com/forum/33917/how-to-callback-operation-using-delegate-in-c-sharp)?

## Replies

### Reply by Aryan Kumar

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:

```plaintext
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.


---

Original Source: https://www.mindstick.com/forum/159924/how-to-create-a-timeout-using-a-promise-to-cancel-a-long-running-asynchronous-operation

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
