lazy.js 858 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. "use strict";
  2. var isFunction = require("../function/is-function");
  3. module.exports = function (executor) {
  4. var Constructor;
  5. if (isFunction(this)) {
  6. Constructor = this;
  7. } else if (typeof Promise === "function") {
  8. Constructor = Promise;
  9. } else {
  10. throw new TypeError("Could not resolve Promise constuctor");
  11. }
  12. var lazyThen;
  13. var promise = new Constructor(function (resolve, reject) {
  14. lazyThen = function (onSuccess, onFailure) {
  15. if (!hasOwnProperty.call(this, "then")) {
  16. // Sanity check
  17. throw new Error("Unexpected (inherited) lazy then invocation");
  18. }
  19. try {
  20. executor(resolve, reject);
  21. } catch (reason) {
  22. reject(reason);
  23. }
  24. delete this.then;
  25. return this.then(onSuccess, onFailure);
  26. };
  27. });
  28. return Object.defineProperty(promise, "then", {
  29. configurable: true,
  30. writable: true,
  31. value: lazyThen
  32. });
  33. };