Skip to content

Instantly share code, notes, and snippets.

@gm50x
Created December 8, 2020 13:15
Show Gist options
  • Save gm50x/93944758b7aa9c187da48d41ba48e6ac to your computer and use it in GitHub Desktop.
Save gm50x/93944758b7aa9c187da48d41ba48e6ac to your computer and use it in GitHub Desktop.
/***************************************************
* Getúlio Magela Silva (gm50x)
*
* Running Instructions:
* node async-iterators {for-each|for-of|map}
*
* Reference Material (NOT MINE):
* https://zellwk.com/blog/async-await-in-loops/
***************************************************/
const getRandomInt = (max = 1) => Math.floor(Math.random() * Math.floor(max))
const getRandomIntAsync = max => new Promise(resolve => setTimeout(() => resolve(getRandomInt(max)), 1000))
const _map = () => new Promise(async (resolve) =>{
console.log('-----ASYNC MAP-----')
const fruits = [
{ name: 'Apple', price: 1 },
{ name: 'Banana', price: 1 },
{ name: 'Grapes', price: 1 }
]
const items = fruits.map(i => ({...i}))
const raisedItems = await Promise.all(items.map(async item => {
const raise = 1 + await getRandomIntAsync(10)
return {...item, price: item.price * raise}
}))
console.log('items mapped after a raise', raisedItems)
console.log('-----ASYNC MAP DONE-----')
resolve();
})
const _forEach = () => new Promise(async (resolve) => {
console.log('-----ASYNC FOR-----')
const fruits = [
{ name: 'Apple', price: 1 },
{ name: 'Banana', price: 1 },
{ name: 'Grapes', price: 1 }
]
const items = fruits.map(i => ({...i}))
items.forEach(async item => {
const raise = 1 + await getRandomIntAsync(10)
item.price *= raise
console.log('item price in loop', item)
})
console.log('original items after forEach', items)
console.log('-----ASYNC FOR DONE-----')
resolve()
})
const _forOf = () => new Promise(async (resolve) => {
console.log('-----ASYNC FOR..OF-----')
const fruits = [
{ name: 'Apple', price: 1 },
{ name: 'Banana', price: 1 },
{ name: 'Grapes', price: 1 }
]
const items = fruits.map(i => ({...i}))
console.log('propper loop manipulation')
for (const item of items) {
const raise = 1 + await getRandomIntAsync(10)
item.price *= raise
}
console.log('after loop manipulation', items)
console.log('-----ASYNC FOR..OF DONE-----')
resolve()
})
const main = async ([n, entrypoint, selectedOption]) => {
const options = {'for-each': _forEach, 'for-of': _forOf, 'map': _map}
if (!selectedOption){
console.log('no option selected. enter one of the following options:', Object.keys(options).join(', '))
} else {
options[selectedOption]()
}
}
main(process.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment