"For the sake of this question, assume the part of the code that is throwing the Error is in another named function, so it doesn't have access to the reject function." – Christopher Shroba
"does this (non-existent in your code) function return a Promise?" – Jaromanda X
"Yes, the other function returns a promise normally, but because an asynchronous function inside that function is throwing an Error, the entire function is throwing an Error." – Christopher Shroba
Well next time post your code, because your ability to describe the problem with English will never be as good as actual code. By "asynchronous function" do you mean a function that returns a promise? If so ...
It doesn't matter how deep the errors throw in your Promises. Here's an example function three
which calls a function two
which calls a function one
which has potential to throw an Error in the event the JSON is formed poorly. Each step makes a valuable contribution to the final computation, but in the event one
throw an error, it will bubble up through the entire chain of Promises.
const one = (json) => new Promise((resolve, reject) => {
resolve(JSON.parse(json))
})
const two = (json) => one(json).then(data => data.hello)
const three = (json) => two(json).then(hello => hello.toUpperCase())
three('{"hello":"world"}').then(console.log, console.error)
// "WORLD"
three('bad json').then(console.log, console.error)
// Error: unexpected token b in JSON at position 0
Otherwise by "asynchronous function" you mean it's a function that does not return a Promise and maybe uses a continuation instead? In which case, we'll modify one
to wrap the async function in a promise, then two
and three
will work the same. Of importance, I did not use try
/catch
in any of my Promise functions
// continuation passing style async function
const asyncParse = (json, k) => {
try {
k(null, JSON.parse(json))
}
catch (err) {
k(err)
}
}
// one now wraps asyncParse in a promise
const one = (json) => new Promise((resolve, reject) => {
asyncParse(json, (err, data) => {
if (err)
reject(err)
else
resolve(data)
})
})
// everything below stays the same
const two = (json) => one(json).then(data => data.hello)
const three = (json) => two(json).then(hello => hello.toUpperCase())
three('{"hello":"world"}').then(console.log, console.error)
// "WORLD"
three('bad json').then(console.log, console.error)
// Error: unexpected token b in JSON at position 0
Oh, and if you have an a function f
which does not function in either of these two ways – ie function that throws an error but doesn't return a promise or send the error to the continuation - you're dealing with a piece of rubbish and the code you write to depend on f
will be rubbish too.