Advertisement
Guest User

Untitled

a guest
Sep 18th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. // Constructing
  2. // 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.
  3.  
  4. var PENDING = 0;
  5. var FULFILLED = 1;
  6. var REJECTED = 2;
  7.  
  8. function Promise(fn) {
  9. // store state which can be PENDING, FULFILLED or REJECTED
  10. var state = PENDING;
  11.  
  12. // store value once FULFILLED or REJECTED
  13. var value = null;
  14.  
  15. // store sucess & failure handlers
  16. var handlers = [];
  17.  
  18. function fulfill(result) {
  19. state = FULFILLED;
  20. value = result;
  21. }
  22.  
  23. function reject(error) {
  24. state = REJECTED;
  25. value = error;
  26. }
  27.  
  28. function resolve(result) {
  29. try {
  30. var then = getThen(result);
  31. if (then) {
  32. doResolve(then.bind(result), resolve, reject)
  33. return
  34. }
  35. fulfill(result);
  36. } catch (e) {
  37. reject(e);
  38. }
  39. }
  40.  
  41. doResolve(fn, resolve, reject);
  42. }
  43.  
  44. // 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