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