method.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. };