Why is it possible to try-catch an async-await call?

后端 未结 2 2022
时光说笑
时光说笑 2021-01-13 22:30

There is a common anti pattern in JavaScript:

function handleDataClb(err, data) {
    if(!data) throw new Error(\'no data found\');
    // handle data... 
}          


        
2条回答
  •  旧时难觅i
    2021-01-13 23:00

    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:

    • It can evaluate like a plain expression, to the result value of that
    • It can evaluate like a throw statement, causing an exception
    • It can evaluate like a return statement, causing only finally statements to be evaluated before ending the function

    On 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 awaited 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.

提交回复
热议问题