Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Dummy list of offer keys
- const availableOffers = [
- '26DDA5B1-EAE5-4C18-8886-2285FD1CA3AE',
- '4C7BBB85-A6B6-48E1-9ED0-E5675446AB1C',
- 'D677E31B-A597-4AF6-B2AD-CE66715BABDC',
- '613579A3-2B5A-4FB0-93BF-287848CB190F',
- '5C5D3250-354A-4A04-BE2A-2516A13B361D'
- ]
- // Dummy list of offer details (key/value pair)
- const offerDetails = {
- '26DDA5B1-EAE5-4C18-8886-2285FD1CA3AE': 'This is a good offer',
- '4C7BBB85-A6B6-48E1-9ED0-E5675446AB1C': 'This is a better offer',
- 'D677E31B-A597-4AF6-B2AD-CE66715BABDC': 'This is an extremely lucrative offer',
- '613579A3-2B5A-4FB0-93BF-287848CB190F': 'This offer will know your socks off',
- '5C5D3250-354A-4A04-BE2A-2516A13B361D': 'This offer is a once in a lifetime oppertuntiy'
- }
- function getList() {
- /**
- * Wait for 5 seconds
- * Then return the availableOffers list
- * (Using setTimeout to fake slow ajax request)
- */
- return new Promise((resolve, reject) => {
- // Wait 5 seconds, then return stuff
- setTimeout(wait => {
- resolve(availableOffers) // Returns available offers
- }, 2000)
- })
- }
- function getItem(id) {
- /**
- * Wait for 2 seconds
- * Then return a key/value pair from the offerDetails list
- * (Using setTimeout to fake slow ajax request)
- */
- return new Promise((resolve, reject) => {
- // Wait 2 seconds, then return stuff
- setTimeout(wait => {
- return resolve(offerDetails[id]) // Returns offer by ID
- }, 2000)
- })
- }
- async function pretendThatItsSync() {
- /**
- * Async function
- * It almost looks like sync code
- * Using the await statement, we can wait for our dependencies to resolve
- * BUT waiting does not mean blocking - our application is still async
- *
- * We will perform 2 fake REST/Ajax calls and push the results to a list
- * At the end we will print out the list
- */
- // The endresult is life!
- const endresult = []
- // Wait for for the function to return the list
- const offers = await getList()
- // Iterate over the offers list
- for (let offer of offers) {
- // Wait for each function to return the details
- let item = await getItem(offer)
- // Then push the result
- endresult.push(item)
- }
- // Finally print out the endresult list
- // It's complete and not just partially populated!
- console.log(endresult)
- }
- // See it in action
- pretendThatItsSync()
Add Comment
Please, Sign In to add comment