index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. var Promise = require('promise');
  2. var isPromise = require('is-promise');
  3. var nextTick;
  4. if (typeof setImmediate === 'function') nextTick = setImmediate
  5. else if (typeof process === 'object' && process && process.nextTick) nextTick = process.nextTick
  6. else nextTick = function (cb) { setTimeout(cb, 0) }
  7. module.exports = nodeify;
  8. function nodeify(promise, cb) {
  9. if (typeof cb !== 'function') return promise;
  10. return promise
  11. .then(function (res) {
  12. nextTick(function () {
  13. cb(null, res);
  14. });
  15. }, function (err) {
  16. nextTick(function () {
  17. cb(err);
  18. });
  19. });
  20. }
  21. function nodeifyThis(cb) {
  22. return nodeify(this, cb);
  23. }
  24. nodeify.extend = extend;
  25. nodeify.Promise = NodeifyPromise;
  26. function extend(prom) {
  27. if (prom && isPromise(prom)) {
  28. prom.nodeify = nodeifyThis;
  29. var then = prom.then;
  30. prom.then = function () {
  31. return extend(then.apply(this, arguments));
  32. };
  33. return prom;
  34. } else if (typeof prom === 'function') {
  35. prom.prototype.nodeify = nodeifyThis;
  36. } else {
  37. Promise.prototype.nodeify = nodeifyThis;
  38. }
  39. }
  40. function NodeifyPromise(fn) {
  41. if (!(this instanceof NodeifyPromise)) {
  42. return new NodeifyPromise(fn);
  43. }
  44. Promise.call(this, fn);
  45. extend(this);
  46. }
  47. NodeifyPromise.prototype = Object.create(Promise.prototype);
  48. NodeifyPromise.prototype.constructor = NodeifyPromise;