You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 1.8KB

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