method.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. "use strict";
  2. module.exports =
  3. function(Promise, INTERNAL, tryConvertToPromise, apiRejection) {
  4. var util = require("./util.js");
  5. var tryCatch = util.tryCatch;
  6. Promise.method = function (fn) {
  7. if (typeof fn !== "function") {
  8. throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  9. }
  10. return function () {
  11. var ret = new Promise(INTERNAL);
  12. ret._captureStackTrace();
  13. ret._pushContext();
  14. var value = tryCatch(fn).apply(this, arguments);
  15. ret._popContext();
  16. ret._resolveFromSyncValue(value);
  17. return ret;
  18. };
  19. };
  20. Promise.attempt = Promise["try"] = function (fn, args, ctx) {
  21. if (typeof fn !== "function") {
  22. return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
  23. }
  24. var ret = new Promise(INTERNAL);
  25. ret._captureStackTrace();
  26. ret._pushContext();
  27. var value = util.isArray(args)
  28. ? tryCatch(fn).apply(ctx, args)
  29. : tryCatch(fn).call(ctx, args);
  30. ret._popContext();
  31. ret._resolveFromSyncValue(value);
  32. return ret;
  33. };
  34. Promise.prototype._resolveFromSyncValue = function (value) {
  35. if (value === util.errorObj) {
  36. this._rejectCallback(value.e, false, true);
  37. } else {
  38. this._resolveCallback(value, true);
  39. }
  40. };
  41. };