Guest User

Untitled

a guest
Jul 21st, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. function getMetric1Data() {
  2. // Some API call that takes 500ms to fetch data
  3. return new Promise(resolve => {
  4. setTimeout(() => {
  5. resolve("Got metric 1 data");
  6. }, 500);
  7. });
  8. }
  9.  
  10. function getMetric2Data() {
  11. // Some API call that takes 1000ms to fetch data
  12. return new Promise(resolve => {
  13. setTimeout(() => {
  14. resolve("Got metric 2 data");
  15. }, 1000);
  16. });
  17. }
  18.  
  19. function getMetric3Data() {
  20. // Some API call that takes 500ms to fetch data
  21. return new Promise(resolve => {
  22. setTimeout(() => {
  23. resolve("Got metric 3 data");
  24. }, 500);
  25. });
  26. }
  27.  
  28. // Fetching the data using only Async/Await. Process takes ~2000ms
  29. (async () => {
  30. const startTime = Date.now();
  31.  
  32. const metric1Data = await getMetric1Data();
  33. const metric2Data = await getMetric2Data();
  34. const metric3Data = await getMetric3Data();
  35.  
  36. const dataSet = [metric1Data, metric2Data, metric3Data];
  37.  
  38. console.log("Data set from only async/await:", dataSet);
  39.  
  40. const endTime = Date.now();
  41.  
  42. console.log(
  43. "Only Async/Await Process took: " + (endTime - startTime) + " ms"
  44. );
  45. })();
  46.  
  47. // Fetching the data using Promise.all w/ Async/Await. Process takes ~1000ms
  48. (async () => {
  49. const startTime = Date.now();
  50.  
  51. const dataSet = await Promise.all([
  52. getMetric1Data(),
  53. getMetric2Data(),
  54. getMetric3Data()
  55. ]);
  56.  
  57. console.log("Data set from Promise.all w/ async/await:", dataSet);
  58.  
  59. const endTime = Date.now();
  60.  
  61. console.log(
  62. "Promise.all with Async/Await Process took: " +
  63. (endTime - startTime) +
  64. " ms"
  65. );
  66. })();
Add Comment
Please, Sign In to add comment