Search code examples
javascripttypescriptpromisees6-promise

Optional catch in javascript promises


The following is valid:

new Promise<void>((resolve, reject) => {
      reject()
    })
    .then(() => {})
    .catch(() => {})

But I might not always care about the error. Is there a way to make the catch optional?

I tried this but it didn't work:

new Promise<void>((resolve, reject?) => {
      if (reject) reject()
    })
    .then(() => {})

Error: Uncaught (in promise): undefined


Solution

  • Is there a way to make the catch optional?

    No. If you are using a promise that might error, you need to handle that (or propagate it to your caller).

    Of course if you create the promise yourself, rejecting it is optional, and you can choose to never reject your promises so that you won't need to handle any errors. But if there are errors from promises that you are using, and you want to ignore them, you must do so explicitly. Just write

    somePromise.catch(e => void e);
    // or             () => { /* ignore */ }
    // or             function ignore() {}