0

I am trying to write a NodeJS script that will return gracefully if it takes too long.

So far I have:

async function willTimeout(){
  try{
    new Promise((resolve, reject) => {
      setTimeout(reject, 1, "timeout");
    }).catch(error => {
      throw error;
    });
    await variableLengthFunction()
  }catch{
    //Handle error gracefully here
  }
}

This doesn't work because the .catch() in the promise doesn't return gracefully as it is an unhandled promise rejection. Is there any way to return an error from a promise that is caught by the encompassing try block?

1 Answers1

0

No. This is exactly why you don't do that.

You have to either await it:

async function willTimeout() {
  try {
    await somePromise
  } catch (e) {
    // Handle error gracefully here
  }
}

or use .then()/.catch():

function willTimeout() {
  return somePromise.catch(e => {
    // Handle error gracefully here
  });
}

I am trying to write a NodeJS script that will return gracefully if it takes too long.

For that, see Timeout in async/await:

async function willTimeout() {
  try {
    return await Promise.race([
      new Promise((resolve, reject) => {
        setTimeout(reject, 1, new Error("timeout"));
      }),
      variableLengthFunction()
    ]);
  } catch(err) {
    // Handle error from `variableLengthFunction` or timeout gracefully here
  }
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375