Guest User

Untitled

a guest
Apr 25th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. //Stupid "Bitmain" question about resolving promises.
  2. //Run 3+ promises and check hoe many resolved and how many failed
  3.  
  4. //Stats variable
  5. const stats = {success: 0, failed: 0};
  6.  
  7. //Some promise
  8. const p = new Promise((resolve, reject) => {
  9. if(true) resolve();
  10. reject()
  11. });
  12.  
  13. //Loop on set stats
  14. const pArr = [p,p,p];
  15. const run = () => {
  16. return new Promise(resolve => {
  17. for(let promise of pArr) {
  18. promise
  19. .then(() => {
  20. stats.success++;
  21. //Resolve the run after all promises resolves
  22. if(stats.success + stats.failed === pArr.length) resolve(stats);
  23. })
  24. .catch(() => {
  25. stats.failed++;
  26. //Resolve the run after all promises resolves
  27. if(stats.success + stats.failed === pArr.length) resolve(stats);
  28. })
  29. }
  30. });
  31. };
  32.  
  33. run().then(console.log);
  34.  
  35. //It's a stupid now because the question but because their answer includes Promise.all and
  36. //wrapping each promise in another "fake" promise that always resolve it.
Add Comment
Please, Sign In to add comment