Guest User

Untitled

a guest
Nov 21st, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. // Dummy list of offer keys
  2. const availableOffers = [
  3. '26DDA5B1-EAE5-4C18-8886-2285FD1CA3AE',
  4. '4C7BBB85-A6B6-48E1-9ED0-E5675446AB1C',
  5. 'D677E31B-A597-4AF6-B2AD-CE66715BABDC',
  6. '613579A3-2B5A-4FB0-93BF-287848CB190F',
  7. '5C5D3250-354A-4A04-BE2A-2516A13B361D'
  8. ]
  9.  
  10. // Dummy list of offer details (key/value pair)
  11. const offerDetails = {
  12. '26DDA5B1-EAE5-4C18-8886-2285FD1CA3AE': 'This is a good offer',
  13. '4C7BBB85-A6B6-48E1-9ED0-E5675446AB1C': 'This is a better offer',
  14. 'D677E31B-A597-4AF6-B2AD-CE66715BABDC': 'This is an extremely lucrative offer',
  15. '613579A3-2B5A-4FB0-93BF-287848CB190F': 'This offer will know your socks off',
  16. '5C5D3250-354A-4A04-BE2A-2516A13B361D': 'This offer is a once in a lifetime oppertuntiy'
  17. }
  18.  
  19. function getList() {
  20. /**
  21. * Wait for 5 seconds
  22. * Then return the availableOffers list
  23. * (Using setTimeout to fake slow ajax request)
  24. */
  25.  
  26. return new Promise((resolve, reject) => {
  27.  
  28. // Wait 5 seconds, then return stuff
  29. setTimeout(wait => {
  30. resolve(availableOffers) // Returns available offers
  31. }, 2000)
  32.  
  33. })
  34. }
  35.  
  36. function getItem(id) {
  37. /**
  38. * Wait for 2 seconds
  39. * Then return a key/value pair from the offerDetails list
  40. * (Using setTimeout to fake slow ajax request)
  41. */
  42.  
  43. return new Promise((resolve, reject) => {
  44.  
  45. // Wait 2 seconds, then return stuff
  46. setTimeout(wait => {
  47. return resolve(offerDetails[id]) // Returns offer by ID
  48. }, 2000)
  49. })
  50.  
  51. }
  52.  
  53.  
  54. async function pretendThatItsSync() {
  55. /**
  56. * Async function
  57. * It almost looks like sync code
  58. * Using the await statement, we can wait for our dependencies to resolve
  59. * BUT waiting does not mean blocking - our application is still async
  60. *
  61. * We will perform 2 fake REST/Ajax calls and push the results to a list
  62. * At the end we will print out the list
  63. */
  64.  
  65. // The endresult is life!
  66. const endresult = []
  67.  
  68. // Wait for for the function to return the list
  69. const offers = await getList()
  70.  
  71. // Iterate over the offers list
  72. for (let offer of offers) {
  73.  
  74. // Wait for each function to return the details
  75. let item = await getItem(offer)
  76.  
  77. // Then push the result
  78. endresult.push(item)
  79. }
  80.  
  81. // Finally print out the endresult list
  82. // It's complete and not just partially populated!
  83. console.log(endresult)
  84.  
  85. }
  86.  
  87. // See it in action
  88. pretendThatItsSync()
Add Comment
Please, Sign In to add comment