Skip to content

Instantly share code, notes, and snippets.

@crismanNoble
Created December 31, 2019 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crismanNoble/7cb357be5186854bf7a7f9bfc83e19d7 to your computer and use it in GitHub Desktop.
Save crismanNoble/7cb357be5186854bf7a7f9bfc83e19d7 to your computer and use it in GitHub Desktop.
[ASYNC examples] #javascript
//do one thing after another is finished
const doThing = async function(timeout) {
const resp = await fetch(scheduleEndpoint, {method: 'POST', body: params}); //needs to return a promise?
return resp;
}
await doThing(); //do an api call or something async that returns a promise
console.log('all done'); //don't do anything else until that is finished.
//do a bunch of things in series, then do something else
//https://zellwk.com/blog/async-await-in-loops/
const fruitsToGet = ['apple', 'grape', 'pear'];
const forLoop = async _ => {
console.log('Start')
for (let index = 0; index < fruitsToGet.length; index++) {
const fruit = fruitsToGet[index];
const numFruit = await getNumFruit(fruit);
console.log(numFruit);
}
console.log('End');
}
//do a bunch of things in parallel, then do something else
const mapLoop = async _ => {
console.log('Start')
const promises = fruitsToGet.map(async fruit => {
const numFruit = await getNumFruit(fruit)
return numFruit
})
const numFruits = await Promise.all(promises)
console.log(numFruits)
console.log('End')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment