nodeify.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. "use strict";
  2. module.exports = function(Promise) {
  3. var util = require("./util.js");
  4. var async = require("./async.js");
  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 = tryCatch(nodeback).apply(promise._boundTo, [null].concat(val));
  11. if (ret === errorObj) {
  12. async.throwLater(ret.e);
  13. }
  14. }
  15. function successAdapter(val, nodeback) {
  16. var promise = this;
  17. var receiver = promise._boundTo;
  18. var ret = val === undefined
  19. ? tryCatch(nodeback).call(receiver, null)
  20. : tryCatch(nodeback).call(receiver, null, val);
  21. if (ret === errorObj) {
  22. async.throwLater(ret.e);
  23. }
  24. }
  25. function errorAdapter(reason, nodeback) {
  26. var promise = this;
  27. if (!reason) {
  28. var target = promise._target();
  29. var newReason = target._getCarriedStackTrace();
  30. newReason.cause = reason;
  31. reason = newReason;
  32. }
  33. var ret = tryCatch(nodeback).call(promise._boundTo, reason);
  34. if (ret === errorObj) {
  35. async.throwLater(ret.e);
  36. }
  37. }
  38. Promise.prototype.asCallback =
  39. Promise.prototype.nodeify = function (nodeback, 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. };