aboutsummaryrefslogtreecommitdiff
path: root/node_modules/release-zalgo/lib/unwrapSync.js
diff options
context:
space:
mode:
authorFlorian Dold <florian.dold@gmail.com>2017-05-28 00:38:50 +0200
committerFlorian Dold <florian.dold@gmail.com>2017-05-28 00:40:43 +0200
commit7fff4499fd915bcea3fa93b1aa8b35f4fe7a6027 (patch)
tree6de9a1aebd150a23b7f8c273ec657a5d0a18fe3e /node_modules/release-zalgo/lib/unwrapSync.js
parent963b7a41feb29cc4be090a2446bdfe0c1f1bcd81 (diff)
add linting (and some initial fixes)
Diffstat (limited to 'node_modules/release-zalgo/lib/unwrapSync.js')
-rw-r--r--node_modules/release-zalgo/lib/unwrapSync.js54
1 files changed, 54 insertions, 0 deletions
diff --git a/node_modules/release-zalgo/lib/unwrapSync.js b/node_modules/release-zalgo/lib/unwrapSync.js
new file mode 100644
index 000000000..baa130b18
--- /dev/null
+++ b/node_modules/release-zalgo/lib/unwrapSync.js
@@ -0,0 +1,54 @@
+'use strict'
+
+const ExtendableError = require('es6-error')
+
+const constants = require('./constants')
+
+class UnwrapError extends ExtendableError {
+ constructor (thenable) {
+ super('Could not unwrap asynchronous thenable')
+ this.thenable = thenable
+ }
+}
+
+// Logic is derived from the Promise Resolution Procedure, as described in the
+// Promises/A+ specification: https://promisesaplus.com/#point-45
+//
+// Note that there is no cycle detection.
+function unwrapSync (x) {
+ if (!x || typeof x !== 'object' && typeof x !== 'function') {
+ return x
+ }
+
+ const then = x.then
+ if (typeof then !== 'function') return x
+
+ let state = constants.PENDING
+ let value
+ const unwrapValue = y => {
+ if (state === constants.PENDING) {
+ state = constants.RESOLVED
+ value = y
+ }
+ }
+ const unwrapReason = r => {
+ if (state === constants.PENDING) {
+ state = constants.REJECTED
+ value = r
+ }
+ }
+ then.call(x, unwrapValue, unwrapReason)
+
+ if (state === constants.PENDING) {
+ state = constants.ASYNC
+ throw new UnwrapError(x)
+ }
+
+ if (state === constants.RESOLVED) {
+ return unwrapSync(value)
+ }
+
+ // state === REJECTED
+ throw value
+}
+module.exports = unwrapSync