1 | # await-to-js
|
2 |
|
3 | [![NPM version][npm-image]][npm-url]
|
4 | [![Downloads][download-badge]][npm-url]
|
5 |
|
6 | > Async await wrapper for easy error handling
|
7 |
|
8 | ## Pre-requisites
|
9 | You need to use Node 7.6 (or later) or an ES7 transpiler in order to use async/await functionality.
|
10 | You can use babel or typescript for that.
|
11 |
|
12 | ## Install
|
13 |
|
14 | ```sh
|
15 | npm i await-to-js --save
|
16 | ```
|
17 |
|
18 | ## Usage
|
19 |
|
20 | ```js
|
21 | import to from 'await-to-js';
|
22 | // If you use CommonJS (i.e NodeJS environment), it should be:
|
23 | // const to = require('await-to-js').default;
|
24 |
|
25 | async function asyncTaskWithCb(cb) {
|
26 | let err, user, savedTask, notification;
|
27 |
|
28 | [ err, user ] = await to(UserModel.findById(1));
|
29 | if(!user) return cb('No user found');
|
30 |
|
31 | [ err, savedTask ] = await to(TaskModel({userId: user.id, name: 'Demo Task'}));
|
32 | if(err) return cb('Error occurred while saving task');
|
33 |
|
34 | if(user.notificationsEnabled) {
|
35 | [ err ] = await to(NotificationService.sendNotification(user.id, 'Task Created'));
|
36 | if(err) return cb('Error while sending notification');
|
37 | }
|
38 |
|
39 | if(savedTask.assignedUser.id !== user.id) {
|
40 | [ err, notification ] = await to(NotificationService.sendNotification(savedTask.assignedUser.id, 'Task was created for you'));
|
41 | if(err) return cb('Error while sending notification');
|
42 | }
|
43 |
|
44 | cb(null, savedTask);
|
45 | }
|
46 |
|
47 | async function asyncFunctionWithThrow() {
|
48 | const [err, user] = await to(UserModel.findById(1));
|
49 | if (!user) throw new Error('User not found');
|
50 |
|
51 | }
|
52 | ```
|
53 |
|
54 | ## TypeScript usage
|
55 | ```javascript
|
56 | interface ServerResponse {
|
57 | test: number;
|
58 | }
|
59 |
|
60 | const p = Promise.resolve({test: 123});
|
61 |
|
62 | const [err, data] = await to<ServerResponse>(p);
|
63 | console.log(data.test);
|
64 | ```
|
65 |
|
66 | ## License
|
67 |
|
68 | MIT © [Dima Grossman](http://blog.grossman.io) && Tomer Barnea
|
69 |
|
70 | [npm-url]: https://npmjs.org/package/await-to-js
|
71 | [npm-image]: https://img.shields.io/npm/v/await-to-js.svg?style=flat-square
|
72 |
|
73 | [travis-url]: https://travis-ci.org/scopsy/await-to-js
|
74 | [travis-image]: https://img.shields.io/travis/scopsy/await-to-js.svg?style=flat-square
|
75 |
|
76 | [coveralls-url]: https://coveralls.io/r/scopsy/await-to-js
|
77 | [coveralls-image]: https://img.shields.io/coveralls/scopsy/await-to-js.svg?style=flat-square
|
78 |
|
79 | [depstat-url]: https://david-dm.org/scopsy/await-to-js
|
80 | [depstat-image]: https://david-dm.org/scopsy/await-to-js.svg?style=flat-square
|
81 |
|
82 | [download-badge]: http://img.shields.io/npm/dm/await-to-js.svg?style=flat-square
|