-2

I need catch an async exception but i can´t use async/await.

I´m trying to use promises, but it doesn´t work.

An example:

myAsyncFunction().then(function() {
  console.log("EVERYTHING OK");
}).catch(function(error) {
  console.log(error);
});

function myAsyncFunction() {
  return new Promise(function(resolve, reject) {
    externalLibraryFunctionAsyncToApiRequest(); //this function throw error
  });
}

I can´t modify the externalLibraryFunctionAsynToApiRequest.

Can I do anything to catch a possible exception?

Arima
  • 1
  • 1
  • 2
    As written you can't, because `myAsyncFunction` doesn't resolve or reject the promise it creates (and it isn't `async`, so that's an odd name for it). Does `externalLibraryFunctionAsyncToApiRequest()` return a promise? – jonrsharpe Dec 04 '20 at 17:22
  • 2
    `try { externalLibraryFunction.....(); } catch (e) { reject(e); }` – Taplar Dec 04 '20 at 17:22
  • `externalLibraryFunctionAsyncToApiRequest().catch( /* ... */ )` Although, if the external function already returns a promise, [there is no need to a promise constructor](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it), just `return externalLibraryFunctionAsyncToApiRequest()` is enough. – VLAZ Dec 04 '20 at 17:22

1 Answers1

0

It's not clear what externalLibraryFunctionAsyncToApiRequest actually does. But, if you don't resolve or reject your Promise then nothing is going to come back regardless of success or failure.

You should do something like this:

myAsyncFunction().then(function() {
  console.log("EVERYTHING OK");
}).catch(function(error) {
  console.log(error);
});

function myAsyncFunction() {
  return new Promise(function(resolve, reject) {
    try {
      throw 'something happend';
      // If no error resolve();
    } catch (ex) {
      reject(ex);
    }
  });
}
mwilson
  • 12,295
  • 7
  • 55
  • 95
  • If externalLibraryFunctionAsyncToApiRequest function does an ajax call (and other things) and the ajax call can throw errors, can I catch the errors here? – Arima Dec 04 '20 at 17:40
  • Yes. That's correct assuming you're not also doing a try/catch in that function. – mwilson Dec 04 '20 at 18:09