Created
December 31, 2019 15:53
-
-
Save crismanNoble/7cb357be5186854bf7a7f9bfc83e19d7 to your computer and use it in GitHub Desktop.
[ASYNC examples] #javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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