Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. var getTime = (function() {
  2. var startTime = Date.now();
  3. return function() {
  4. return (Date.now() - startTime) / 1000;
  5. };
  6. })();
  7. Array.prototype.asyncMapP = function(callback) {
  8. return Promise.all(this.map(callback));
  9. };
  10. Array.prototype.asyncMapS = async function(callback) {
  11. var res = [];
  12. for (var i = 0; i < this.length; i++) {
  13. res.push(await callback(this[i], i, this));
  14. }
  15. return res;
  16. };
  17.  
  18. function getSquare(i, j, arr) {
  19. console.log(`executing getSquare at ${getTime()}`);
  20. return i * i;
  21. }
  22. function getSquareAsync(i, j, arr) {
  23. return new Promise(resolve =>
  24. setTimeout(() => {
  25. console.log(`executing getSquareAsync at ${getTime()}`);
  26. resolve(i * i);
  27. }, 2000)
  28. );
  29. }
  30.  
  31. async function run() {
  32. var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  33. var result1 = arr.map(getSquare);
  34. console.log(`result1 @ ${getTime()}`, result1);
  35. // result1 is [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]
  36. var result2 = await arr.asyncMapP(getSquareAsync);
  37. console.log(`result2 @ ${getTime()}`, result2);
  38. // result2 is [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]
  39. var result3 = await arr.asyncMapS(getSquareAsync);
  40. console.log(`result3 @ ${getTime()}`, result3);
  41. // result3 is [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]
  42. }
  43.  
  44. run();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement