Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Constructing
- // We now have the completed internal state machine, but we have yet to expose either a method of resolving the promise or of observing it. Lets start by adding a way of resolving the promise.
- var PENDING = 0;
- var FULFILLED = 1;
- var REJECTED = 2;
- function Promise(fn) {
- // store state which can be PENDING, FULFILLED or REJECTED
- var state = PENDING;
- // store value once FULFILLED or REJECTED
- var value = null;
- // store sucess & failure handlers
- var handlers = [];
- function fulfill(result) {
- state = FULFILLED;
- value = result;
- }
- function reject(error) {
- state = REJECTED;
- value = error;
- }
- function resolve(result) {
- try {
- var then = getThen(result);
- if (then) {
- doResolve(then.bind(result), resolve, reject)
- return
- }
- fulfill(result);
- } catch (e) {
- reject(e);
- }
- }
- doResolve(fn, resolve, reject);
- }
- // As you can see, we re-use doResolve because we have another untrusted resolver. The fn is allowed to call both resolve and reject multiple times, and even throw exceptions. It is up to us to ensure that the promise is only resolved or rejected once, and then never transitions into a different state ever again.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement