3 ms·
The brevity and aesthetics of async/await has made me reluctant to move back to any pyramid type async chain. I don't know if it's good practice, but I use type
by JSONwebtoken 9y ago
The brevity and aesthetics of async/await has made me reluctant to move back to any pyramid type async chain. I don't know if it's good practice, but I use typescript to declare an optional null type and just return a null from inside the async function if I need to cancel.
- Mitranim 9y agoPosterus provides coroutines just for that: https://github.com/Mitranim/posterus#routine https://github.com/Mitranim/posterus#routine Posterus coroutines are similar to async/await, but cancelable and free of `await`'s race condition problem (promise can get rejected before `await` attaches a handler).
- taralx 9y agoWhy is that a race? IIRC Promise.then is supposed to invoke the callback immediately (or on next loop) if the promise is already resolved.
- Mitranim 9y agoIt would be race-free if `.then()` was invoked synchronously when evaluating the `await` expression, just like in normal Promise-based code. Currently in V8, there's a delay between evaluating `await` and actually calling `.then()`. If the promise uses a sufficiently nimble scheduler (i.e. based on `process.nextTick`), its unhandled rejection handler may run _in between_, throwing an exception, polluting stderr and possibly killing the process. Example with Posterus: async function main() { try { await Future.fromError('fail') } catch (err) { console.error('caught:', err) } } In Node, this actually produces an unhandled rejection because Posterus's scheduler uses `process.nextTick` and squeezes into this unnecessary delay. Doesn't happen if you `.catch()` manually or just use Posterus coroutines instead of interoping with async/await, but it highlights the incorrect implementation of async/await in the first place. (Or is the spec at fault?)