You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.7 KiB

4 years ago
  1. "use strict";
  2. module.exports =
  3. function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
  4. var util = require("./util");
  5. var tryCatch = util.tryCatch;
  6. Promise.method = function (fn) {
  7. if (typeof fn !== "function") {
  8. throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
  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. var promiseCreated = ret._popContext();
  16. debug.checkForgottenReturns(
  17. value, promiseCreated, "Promise.method", ret);
  18. ret._resolveFromSyncValue(value);
  19. return ret;
  20. };
  21. };
  22. Promise.attempt = Promise["try"] = function (fn) {
  23. if (typeof fn !== "function") {
  24. return apiRejection("expecting a function but got " + util.classString(fn));
  25. }
  26. var ret = new Promise(INTERNAL);
  27. ret._captureStackTrace();
  28. ret._pushContext();
  29. var value;
  30. if (arguments.length > 1) {
  31. debug.deprecated("calling Promise.try with more than 1 argument");
  32. var arg = arguments[1];
  33. var ctx = arguments[2];
  34. value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
  35. : tryCatch(fn).call(ctx, arg);
  36. } else {
  37. value = tryCatch(fn)();
  38. }
  39. var promiseCreated = ret._popContext();
  40. debug.checkForgottenReturns(
  41. value, promiseCreated, "Promise.try", ret);
  42. ret._resolveFromSyncValue(value);
  43. return ret;
  44. };
  45. Promise.prototype._resolveFromSyncValue = function (value) {
  46. if (value === util.errorObj) {
  47. this._rejectCallback(value.e, false);
  48. } else {
  49. this._resolveCallback(value, true);
  50. }
  51. };
  52. };