BobtheMagicMoose
BobtheMagicMoose

Reputation: 2429

How to handle promise and non-promise error catching together

I am executing an array of functions, each of which may return a promise and may return a value. When handling the return value, I want to be able to catch all errors created by the selected function regardless of it being a promise or value. Here's an example of what I wish to accomplish:

const functionA = (v) => {
throw "Value error"
}
const functionB = (v) => new Promise(function(resolve, reject) {
  throw 'Promise error';
})

const functionsArray = [functionA,functionB]
  .map(f=>Promise.resolve(f())) // run function and cast return as promise
  .map(f=>f.catch(console.log)) //add error catching

 

I know I can wrap the function execution in a try/catch block but I would prefer to have a single error catching segment.

Upvotes: 1

Views: 873

Answers (2)

Banned007
Banned007

Reputation: 15

I think you are looking for Promise.all. as @Ry- pointed out its easy to convert the functions to promise using the async keyword on the map, so your code should look like:

Promise.all([functionA,functionB].map(async f=>f())).catch(console.log)

Upvotes: 0

Ry-
Ry-

Reputation: 224963

.then() catches synchronous errors:

const functionsArray = [functionA, functionB]
  .map(f => Promise.resolve().then(f))

There’s a proposal to call this Promise.try.

An async function will also do the trick:

const functionsArray = [functionA, functionB]
  .map(async f => f())

Upvotes: 6

Related Questions