-1

Is there a way to ignore asynchronous errors while calling a function?

Synchronous

function synchronous() {
    console.log('Nice feature');
    throw new Error('Async Error');
}

try {
    synchronous();
    console.log('Succeeded');
} catch (e) {
    console.log('Caught');
}

Console Output:
Nice feature
Caught

Asynchronous

async function asynchronous() {
    console.log('Nice feature');
    throw new Error('Async Error');
}

try {
    asynchronous();
    console.log('Succeeded');
} catch (e) {
    console.log('Caught');
}

Console Output:
Nice feature
Uncaught (in promise) Error: Async Error at asyncFunc

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    You should learn about `await`, `Promise.prototype.catch`, and optionally global error handlers, which catch everything you otherwise forgot to catch. – ASDFGerte Dec 30 '21 at 17:11

2 Answers2

0

two options:

(async () => {
  try {
    await asynchronous();
    console.log('Succeeded');
  } catch (e) {
    console.log('Caught');
  }
});

or

 asynchronous()
       .then(r => {
         console.log('succeeded');
       })
       .catch(e => {
           console.log('caught');
         });
TKoL
  • 13,158
  • 3
  • 39
  • 73
0

I'm not sure if that answers your question, but if "await" for the result of calling asynchronous() function, the error will not occur

benmotyka
  • 179
  • 1
  • 7