Guest User

Untitled

a guest
Jan 21st, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. class Promises {
  2. constructor(fn) {
  3. this.state = 0;
  4. this.value = undefined;
  5. this.todos = [];
  6. fn(() => this.resolve(), () => this.reject());
  7. }
  8. resolve(value) {
  9. if (this.state !== 0) return;
  10. this.state = 1;
  11. this.value = value;
  12. this.run();
  13. }
  14. reject(reason) {
  15. if (this.state !== 0) return;
  16. this.state = 2;
  17. this.value = reason;
  18. this.run();
  19. }
  20. run() {
  21. let callbackName, resolver;
  22. if (this.state === 0) return;
  23. if (this.state === 1) {
  24. callbackName = 'onFulfilled';
  25. resolver = 'resolve';
  26. }
  27. if (this.state === 2) {
  28. callbackName = 'onRejected';
  29. resolver = 'reject';
  30. }
  31. setTimeout(() => {
  32. this.todos.forEach(todo => {
  33. try {
  34. let cb = todo[callbackName];
  35. if (cb) todo.resolve(cb(this.value));
  36. else todo[resolver](this.value);
  37. } catch (e) {
  38. todo.reject(e);
  39. }
  40. this.todos.shift();
  41. });
  42. });
  43. }
  44. then(onFulfilled, onRejected) {
  45. let todo = new Promises(() => {});
  46. todo.onFulfilled =
  47. typeof onFulfilled === 'function' ? onFulfilled : null;
  48. todo.onRejected = typeof onRejected === 'function' ? onRejected : null;
  49. this.todos.push(todo);
  50. this.run();
  51. return todo;
  52. }
  53. }
Add Comment
Please, Sign In to add comment