Advertisement
Guest User

Untitled

a guest
Dec 9th, 2016
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. function makePromisesTraceable() {
  2. var NativePromise = window.Promise;
  3. window.promiseRegistry = [];
  4. window.Promise = function(cb) {
  5. var state = {};
  6. var p = new NativePromise(function(resolve, reject) {
  7. var res = function(v) { state.status = 'resolved'; state.value = v; resolve(v); };
  8. var rej = function(v) { state.status = 'rejected'; state.value = v; reject(v); };
  9. return cb(res, rej);
  10. });
  11. p.callback = cb;
  12. p.state = state;
  13. window.promiseRegistry.push(p);
  14. return p;
  15. };
  16.  
  17. Promise.resolve = function(item) {
  18. return new Promise(function(resolve) { resolve(item); });
  19. };
  20.  
  21. Promise.all = function(arr) {
  22. return new Promise(function(resolve) {
  23. var results = [];
  24. if (arr.length === 0) resolve(results);
  25.  
  26. var pendingCount = arr.length;
  27. arr.forEach(function(val, index) {
  28. Promise.resolve(val).then(function(res) {
  29. results[index] = res;
  30. pendingCount--;
  31. if (pendingCount === 0) resolve(results);
  32. });
  33. });
  34. });
  35. };
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement