nodeify.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. "use strict";
  2. module.exports = function(Promise) {
  3. var util = require("./util");
  4. var async = Promise._async;
  5. var tryCatch = util.tryCatch;
  6. var errorObj = util.errorObj;
  7. function spreadAdapter(val, nodeback) {
  8. var promise = this;
  9. if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
  10. var ret =
  11. tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
  12. if (ret === errorObj) {
  13. async.throwLater(ret.e);
  14. }
  15. }
  16. function successAdapter(val, nodeback) {
  17. var promise = this;
  18. var receiver = promise._boundValue();
  19. var ret = val === undefined
  20. ? tryCatch(nodeback).call(receiver, null)
  21. : tryCatch(nodeback).call(receiver, null, val);
  22. if (ret === errorObj) {
  23. async.throwLater(ret.e);
  24. }
  25. }
  26. function errorAdapter(reason, nodeback) {
  27. var promise = this;
  28. if (!reason) {
  29. var newReason = new Error(reason + "");
  30. newReason.cause = reason;
  31. reason = newReason;
  32. }
  33. var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
  34. if (ret === errorObj) {
  35. async.throwLater(ret.e);
  36. }
  37. }
  38. Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
  39. options) {
  40. if (typeof nodeback == "function") {
  41. var adapter = successAdapter;
  42. if (options !== undefined && Object(options).spread) {
  43. adapter = spreadAdapter;
  44. }
  45. this._then(
  46. adapter,
  47. errorAdapter,
  48. undefined,
  49. this,
  50. nodeback
  51. );
  52. }
  53. return this;
  54. };
  55. };