• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..20-Sep-2020-

dist/H03-May-2022-

README.mdH A D26-Oct-19851.8 KiB9067

package.jsonH A D20-Sep-20201.8 KiB7372

README.md

1[![Travis CI](https://travis-ci.org/digitaldesignlabs/es6-promisify.svg)](https://travis-ci.org/digitaldesignlabs/es6-promisify)
2
3# es6-promisify
4
5Converts callback-based functions to Promise-based functions.
6
7## Install
8
9Install with [npm](https://npmjs.org/package/es6-promisify)
10
11```bash
12npm install --save es6-promisify
13```
14
15## Example
16
17```js
18"use strict";
19
20// Declare variables
21const promisify = require("es6-promisify");
22const fs = require("fs");
23
24// Convert the stat function
25const stat = promisify(fs.stat);
26
27// Now usable as a promise!
28stat("example.txt").then(function (stats) {
29    console.log("Got stats", stats);
30}).catch(function (err) {
31    console.error("Yikes!", err);
32});
33```
34
35## Promisify methods
36```js
37"use strict";
38
39// Declare variables
40const promisify = require("es6-promisify");
41const redis = require("redis").createClient(6379, "localhost");
42
43// Create a promise-based version of send_command
44const client = promisify(redis.send_command, redis);
45
46// Send commands to redis and get a promise back
47client("ping").then(function (pong) {
48    console.log("Got", pong);
49}).catch(function (err) {
50    console.error("Unexpected error", err);
51}).then(function () {
52    redis.quit();
53});
54```
55
56## Handle callback multiple arguments
57```js
58"use strict";
59
60// Declare functions
61function test(cb) {
62    return cb(undefined, 1, 2, 3);
63}
64
65// Declare variables
66const promisify = require("es6-promisify");
67
68// Create promise-based version of test
69const single = promisify(test);
70const multi = promisify(test, {multiArgs: true});
71
72// Discards additional arguments
73single().then(function (result) {
74    console.log(result); // 1
75});
76
77// Returns all arguments as an array
78multi().then(function (result) {
79    console.log(result); // [1, 2, 3]
80});
81```
82
83### Tests
84Test with nodeunit
85```bash
86$ npm test
87```
88
89Published under the [MIT License](http://opensource.org/licenses/MIT).
90