|
| 1 | +# 😪 await-on |
| 2 | + |
| 3 | + |
| 4 | + |
| 5 | + |
| 6 | + |
| 7 | + |
| 8 | + |
| 9 | +really simple error handling with await/async |
| 10 | + |
| 11 | +inspired by [`await-to-js`](https://github.com/scopsy/await-to-js) whose creator [Dima Grossman](http://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/) originally blogged about using destructuring array assignment |
| 12 | + |
| 13 | +## Overview |
| 14 | +This package basically provides 3 syntactical paths to choose from: |
| 15 | +```javascript |
| 16 | +const {on, handler} = require('await-on'); |
| 17 | + |
| 18 | +const fetchData = () => new Promise(/*...*/); |
| 19 | + |
| 20 | +const [err, data] = await on(fetchData()); |
| 21 | +const [err, data] = await handler(fetchData)(); //decorator |
| 22 | +const [err, data] = await fetchData().handle(); //prototype extension |
| 23 | +``` |
| 24 | + |
| 25 | +The goal is to avoid the built-in approach using the `try`/`catch` block pattern: |
| 26 | + |
| 27 | +```javascript |
| 28 | +try{ |
| 29 | + const data = await fetchData(); |
| 30 | + res.send(data); |
| 31 | +}catch(err) { |
| 32 | + res.send(err); |
| 33 | +} |
| 34 | +``` |
| 35 | + |
| 36 | +## Quick Usage |
| 37 | + |
| 38 | +using `on` with the function `fetchData` which returns a Promise that resolve to some result `data`: |
| 39 | +```javascript |
| 40 | +const {on} = require('await-on'); |
| 41 | +const fetchData = () => new Promise(/*...*/); |
| 42 | + |
| 43 | +async function foo(req,res) { |
| 44 | + const [err, data] = await on(fetchData()); |
| 45 | + if(err) res.send(err); |
| 46 | + else res.send(data); |
| 47 | +} |
| 48 | +``` |
| 49 | + |
| 50 | +Using the decorator pattern with `handler` yields some cleaner high level code: |
| 51 | + |
| 52 | +```javascript |
| 53 | +const {handler} = require('await-on'); |
| 54 | +let fetchData = () => new Promise(/*...*/); |
| 55 | +fetchData = handler(fetchData); |
| 56 | + |
| 57 | +async function foo(req,res) { |
| 58 | + const [err, data] = await fetchData(); |
| 59 | + !err ? res.send(data) : res.send(err); |
| 60 | +} |
| 61 | +``` |
| 62 | + |
| 63 | +Finally, using the prototype extension `handle` on Promise types is also clean and is arguably even more readable because it also uses the chaining pattern already standard when working with Promises 🌟 : |
| 64 | + |
| 65 | +```javascript |
| 66 | +require('await-on'); |
| 67 | + |
| 68 | +async function foo(req,res) { |
| 69 | + const [err, data] = await fetchData().handle(); |
| 70 | + !err ? res.send(data) : res.send(err); |
| 71 | +} |
| 72 | +``` |
| 73 | + |
| 74 | +## Type fuzziness |
| 75 | +Non-promises will passthrough same as the behavior of the native `await` |
| 76 | + |
| 77 | +```javascript |
| 78 | +const [err,answer] = await on(42); //not a promise but ok no big deal |
| 79 | +console.log(answer) //> 42 |
| 80 | +``` |
0 commit comments