There is a common anti pattern in JavaScript:
function handleDataClb(err, data) {
if(!data) throw new Error(\'no data found\');
// handle data...
}
Why and how does the
catch
work? How does the coroutine aka async manage to throw the error inside the try-catch?
A yield
or await
expression can have 3 different outcomes:
throw
statement, causing an exceptionreturn
statement, causing only finally
statements to be evaluated before ending the functionOn a suspended generator, this can be achieved by calling either the .next(), .throw() or .return() methods. (Of course there's also a 4th possible outcome, to never get resumed).
…when one of the asyncTask calls results in a promise rejection?
The await
ed value will be Promise.resolve()
d to a promise, then the .then() method gets invoked on it with two callbacks: when the promise fulfills, the coroutine is resumed with a normal value (the promise result), and when the promise rejects, the coroutine is resumed with an abrupt completion (exception - the rejection reason).
You can look at the co library code or the transpiler output - it literally calls gen.throw from the promise rejection callback.