Open In App

How to set Maximum Execution Time for a Promise Await in JavaScript ?

In JavaScript, asynchronous operations are more common, often implemented using promises and async/await syntax. However, there are certain scenarios where we want to set the execution times for these asynchronous operations to prevent them from running indefinitely. In this article, we'll explore various ways to set the maximum execution time for a Promise await in JavaScript.

Using Promise.race() with a Timeout Promise

In this method, we'll use Promise.race() method. This method accepts an iterable of promises as its input and returns a new promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects. In our context, the Promise.race() race between the original promise and a timeout promise and whichever resolves or rejects first is returned.

Example: In this example, we'll create a Promise that simply returns a JavaScript object after a given timeout. We'll use Promise.race to set the maximum execution time.

function fetchData() {
    return new Promise((resolve, reject) => {
        // Simulating an asynchronous operation
        setTimeout(() => {
            const data = { example: "data" };
            resolve(data);
        }, 6000);
        // Resolves after 6 seconds
    });
}
function withTimeout(promise, timeout) {
    return Promise
        .race([
            promise,
            new Promise((_, reject) =>
                setTimeout(() => reject(new Error('Timeout')), timeout)
            )
        ]);
}

async function executeFunction() {
    try {
        const data = await withTimeout(fetchData(), 5000);
        // 5000 milliseconds timeout
        console.log(data);
        // Log fetched data to the console
    } catch (err) {
        console.error(err);
    }
}

executeFunction();

Output:

peek2

Using setTimeout() method and a flag

Here we use setTimeout() method along with a completion flag to set the maximum execution time. If the data fetching operation takes longer than the set timeout, an error shall be thrown. Otherwise, if the data is fetched successfully within the timeout period, the fetched data will be logged to the console.

Example: In this example, we'll create a mainFunction() which is responsible for fetching data asynchronously using fetchData() function. We set a timeout using setTimeout() method for 7 seconds. If the operation doesn't complete within this timeout, an error message is thrown.

function fetchData() {
  return new Promise((resolve, reject) => {
    // Simulating an asynchronous operation
    setTimeout(() => {
      const data = { example: "data" };
      resolve(data);
    }, 5000); // Resolves after 5 seconds
  });
}
async function mainFunction() {
  let completed = false;
  const timeout = 7000; // 7000 milliseconds timeout

  setTimeout(() => {
    if (!completed) {
      console.error(new Error('Timeout'));
    }
  }, timeout);

  try {
    const data = await fetchData();
    console.log(data); // Log fetched data to the console
    completed = true;
  } catch (err) {
    console.error(err);
  }
}

mainFunction();

Output:

peek3

Article Tags :