forked from domenic/promises-unwrapping
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testable-implementation.js
403 lines (332 loc) · 11 KB
/
testable-implementation.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
"use strict";
var assert = require("assert");
var UNSET = { "unset": "UNSET" };
// NOTE!!! This is not normal JavaScript; it's used as a sanity check for the spec. JavaScript promises do not work this
// way, e.g. they have methods instead of these capitalized functions! Do not use this for anything real!
var ThenableCoercions = new WeakMap();
function NewlyCreatedPromiseObject() {
// The specs say "newly-created X object" to basically mean "`X[@@create]()`, or fall back to the default." We don't
// want to re-create the entire @@create spec mechanism, but we can produce something more or less the same.
var promise = Object.create(Promise.prototype);
promise._isPromise = true;
promise._following = UNSET;
promise._value = UNSET;
promise._reason = UNSET;
promise._promiseConstructor = Promise;
promise._derived = [];
return promise;
}
function IsPromise(x) {
return IsObject(x) && x._isPromise;
}
function Resolve(p, x) {
if (is_set(p._following) || is_set(p._value) || is_set(p._reason)) {
return;
}
if (IsPromise(x)) {
if (SameValue(p, x)) {
var selfResolutionError = new TypeError("Tried to resolve a promise with itself!");
SetReason(p, selfResolutionError);
} else if (is_set(x._following)) {
p._following = x._following;
x._following._derived.push({ derivedPromise: p, onFulfilled: undefined, onRejected: undefined });
} else if (is_set(x._value)) {
SetValue(p, x._value);
} else if (is_set(x._reason)) {
SetReason(p, x._reason);
} else {
p._following = x;
x._derived.push({ derivedPromise: p, onFulfilled: undefined, onRejected: undefined });
}
} else {
SetValue(p, x);
}
}
function Reject(p, r) {
if (is_set(p._following) || is_set(p._value) || is_set(p._reason)) {
return;
}
SetReason(p, r);
}
function Then(p, onFulfilled, onRejected) {
if (is_set(p._following)) {
return Then(p._following, onFulfilled, onRejected);
} else {
var C = UNSET, q;
try {
C = p.constructor;
} catch (e) {
q = NewlyCreatedPromiseObject();
Reject(q, e);
}
if (is_set(C)) {
q = GetDeferred(C).promise;
var derived = { derivedPromise: q, onFulfilled: onFulfilled, onRejected: onRejected };
UpdateDerivedFromPromise(derived, p);
}
return q;
}
}
function PropagateToDerived(p) {
assert((is_set(p._value) && !is_set(p._reason)) || (is_set(p._reason) && !is_set(p._value)));
p._derived.forEach(function (derived) {
UpdateDerived(derived, p);
});
// As per the note in the spec, this is not necessary, as we can verify by commenting it out.
p._derived = [];
}
function UpdateDerived(derived, originator) {
assert((is_set(originator._value) && !is_set(originator._reason)) || (is_set(originator._reason) && !is_set(originator._value)));
if (is_set(originator._value)) {
if (IsObject(originator._value)) {
QueueAMicrotask(function () {
if (ThenableCoercions.has(originator._value)) {
var coercedAlready = ThenableCoercions.get(originator._value);
UpdateDerivedFromPromise(derived, coercedAlready);
} else {
var then = UNSET;
try {
then = originator._value.then;
} catch (e) {
UpdateDerivedFromReason(derived, e);
}
if (is_set(then)) {
if (IsCallable(then)) {
var coerced = CoerceThenable(originator._value, then);
UpdateDerivedFromPromise(derived, coerced);
} else {
UpdateDerivedFromValue(derived, originator._value);
}
}
}
});
} else {
UpdateDerivedFromValue(derived, originator._value);
}
} else if (is_set(originator._reason)) {
UpdateDerivedFromReason(derived, originator._reason);
}
}
function UpdateDerivedFromValue(derived, value) {
if (IsCallable(derived.onFulfilled)) {
CallHandler(derived.derivedPromise, derived.onFulfilled, value);
} else {
SetValue(derived.derivedPromise, value);
}
}
function UpdateDerivedFromReason(derived, reason) {
if (IsCallable(derived.onRejected)) {
CallHandler(derived.derivedPromise, derived.onRejected, reason);
} else {
SetReason(derived.derivedPromise, reason);
}
}
function UpdateDerivedFromPromise(derived, promise) {
if (is_set(promise._value) || is_set(promise._reason)) {
UpdateDerived(derived, promise);
} else {
promise._derived.push(derived);
}
}
function CoerceThenable(thenable, then) {
// Missing assert: execution context stack is empty. Very hard to test; maybe could use `(new Error()).stack`?
var p = NewlyCreatedPromiseObject();
var resolve = function (x) {
Resolve(p, x);
}
var reject = function (r) {
Reject(p, r);
}
try {
then.call(thenable, resolve, reject);
} catch (e) {
Reject(p, e);
}
ThenableCoercions.set(thenable, p);
return p;
}
function CallHandler(derivedPromise, handler, argument) {
QueueAMicrotask(function () {
var v = UNSET;
try {
v = handler(argument);
} catch (e) {
Reject(derivedPromise, e);
}
if (is_set(v)) {
Resolve(derivedPromise, v);
}
});
}
function SetValue(p, value) {
assert(!is_set(p._value) && !is_set(p._reason));
p._value = value;
p._following = UNSET;
PropagateToDerived(p);
}
function SetReason(p, reason) {
assert(!is_set(p._value) && !is_set(p._reason));
p._reason = reason;
p._following = UNSET;
PropagateToDerived(p);
}
function ToPromise(C, x) {
if (IsPromise(x) && SameValue(x._promiseConstructor, C) === true) {
return x;
} else {
var deferred = GetDeferred(C);
deferred.resolve(x);
return deferred.promise;
}
}
function GetDeferred(C) {
var promise, resolve, reject;
if (IsConstructor(C)) {
var resolver = function (firstArgument, secondArgument) {
resolve = firstArgument;
reject = secondArgument;
};
promise = new C(resolver);
} else {
promise = NewlyCreatedPromiseObject();
resolve = function (x) {
Resolve(promise, x);
};
reject = function (r) {
Reject(promise, r);
};
}
return { promise: promise, resolve: resolve, reject: reject };
}
//////
// ES/environment functions
function IsObject(x) {
return (typeof x === "object" && x !== null) || typeof x === "function";
}
function IsCallable(x) {
return typeof x === "function";
}
function IsConstructor(x) {
// The actual steps include testing whether `x` has a `[[Construct]]` internal method.
// This is NOT possible to determine in pure JS, so this is just an approximation.
return typeof x === "function";
}
function SameValue(x, y) {
return Object.is(x, y);
}
function QueueAMicrotask(func) {
process.nextTick(function () {
func();
});
}
//////
// Internal helpers (for clarity)
function is_set(internalPropertyValue) {
return internalPropertyValue !== UNSET;
}
function define_method(object, methodName, method) {
Object.defineProperty(object, methodName, {
value: method,
configurable: true,
writable: true
});
}
//////
// ES manifestation
function Promise(resolver) {
// Because we don't want to implement the whole @@create mechanism, this doesn't work quite the same as is specced;
// we take a shortcut by using `NewlyCreatedPromiseObject`. But the result is roughly the same, modulo some
// subtleties when it comes to subclassing and the like.
if (!IsCallable(resolver)) {
throw new TypeError("non-callable resolver function");
}
var promise = NewlyCreatedPromiseObject();
var resolve = function (x) {
Resolve(promise, x);
};
var reject = function (r) {
Reject(promise, r);
};
try {
resolver.call(undefined, resolve, reject);
} catch (e) {
Reject(promise, e);
}
return promise;
}
define_method(Promise, "resolve", function (x) {
var deferred = GetDeferred(this);
deferred.resolve(x);
return deferred.promise;
});
define_method(Promise, "reject", function (r) {
var deferred = GetDeferred(this);
deferred.reject(r);
return deferred.promise;
});
define_method(Promise, "cast", function (x) {
return ToPromise(this, x);
});
define_method(Promise, "race", function (iterable) {
var deferred = GetDeferred(this);
for (var nextValue of iterable) {
var nextPromise = ToPromise(this, nextValue);
Then(nextPromise, deferred.resolve, deferred.reject);
}
return deferred.promise;
});
define_method(Promise, "all", function (iterable) {
var deferred = GetDeferred(this);
var values = [];
var countdown = 0;
var index = 0;
for (var nextValue of iterable) {
var currentIndex = index;
var nextPromise = ToPromise(this, nextValue);
var onFulfilled = function (v) {
Object.defineProperty(values, currentIndex, { value: v, writable: true, enumerable: true, configurable: true });
countdown = countdown - 1;
if (countdown === 0) {
deferred.resolve(values);
}
};
Then(nextPromise, onFulfilled, deferred.reject);
index = index + 1;
countdown = countdown + 1;
}
if (index === 0) {
deferred.resolve(values);
}
return deferred.promise;
});
define_method(Promise.prototype, "then", function (onFulfilled, onRejected) {
return Then(this, onFulfilled, onRejected);
});
define_method(Promise.prototype, "catch", function (onRejected) {
return this.then(undefined, onRejected);
});
//////
// Promises/A+ specification test adapter
// A `done` function is useful for tests, to ensure no assertion errors are ignored.
exports.done = function (promise, onFulfilled, onRejected) {
promise.then(onFulfilled, onRejected).catch(function (reason) {
process.nextTick(function () {
throw reason;
});
});
};
exports.pending = function () {
var resolvePromise, rejectPromise;
var promise = new Promise(function (resolve, reject) {
resolvePromise = resolve;
rejectPromise = reject;
});
// NB: Promises/A+ tests never pass promises (or thenables) to the adapter's `fulfill` method, so using
// `resolvePromise` is equivalent to some hypothetical fulfiller.
return {
promise: promise,
fulfill: resolvePromise,
reject: rejectPromise
};
};
exports.Promise = Promise;