nodeback.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. "use strict";
  2. var util = require("./util");
  3. var maybeWrapAsError = util.maybeWrapAsError;
  4. var errors = require("./errors");
  5. var OperationalError = errors.OperationalError;
  6. var es5 = require("./es5");
  7. function isUntypedError(obj) {
  8. return obj instanceof Error &&
  9. es5.getPrototypeOf(obj) === Error.prototype;
  10. }
  11. var rErrorKey = /^(?:name|message|stack|cause)$/;
  12. function wrapAsOperationalError(obj) {
  13. var ret;
  14. if (isUntypedError(obj)) {
  15. ret = new OperationalError(obj);
  16. ret.name = obj.name;
  17. ret.message = obj.message;
  18. ret.stack = obj.stack;
  19. var keys = es5.keys(obj);
  20. for (var i = 0; i < keys.length; ++i) {
  21. var key = keys[i];
  22. if (!rErrorKey.test(key)) {
  23. ret[key] = obj[key];
  24. }
  25. }
  26. return ret;
  27. }
  28. util.markAsOriginatingFromRejection(obj);
  29. return obj;
  30. }
  31. function nodebackForPromise(promise, multiArgs) {
  32. return function(err, value) {
  33. if (promise === null) return;
  34. if (err) {
  35. var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
  36. promise._attachExtraTrace(wrapped);
  37. promise._reject(wrapped);
  38. } else if (!multiArgs) {
  39. promise._fulfill(value);
  40. } else {
  41. var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};
  42. promise._fulfill(args);
  43. }
  44. promise = null;
  45. };
  46. }
  47. module.exports = nodebackForPromise;